You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中map无法实时渲染数组元素的问题排查

问题:待办事项添加后页面无法实时更新,控制台可见数组已更新

在实现待办事项添加笔记功能时,元素已成功推入数组且控制台能看到数组变化,但页面无需刷新却无法实时显示新元素,localStorage的实现逻辑无误。相关代码如下:

import "./styles.css";
import { useState, useRef, useEffect } from "react";
export default function App() {
  let array = [];
  let notes = localStorage.getItem("notes");
  if (notes !== null) {
    array = JSON.parse(notes);
  }
  const Add = () => {
    array.push(one.current.value);
    localStorage.setItem("notes", JSON.stringify(array));
    console.log("after adding the value -> ", array);
  };
  const one = useRef(null);
  return (
    <>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <div className="align">
          <input ref={one} />
          <br />
          <br />
          <button onClick={Add}>Add</button>
        </div>
        <div className="align">
          {array.map((e, index) => {
            console.log(index, "-> ", e);
            return (
              <div key={index} index={index + 1} name={e}>
                {e}
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

解决方案

问题核心是你用了普通变量array存储待办数据,而React仅在状态(state)或属性(props)变化时触发组件重渲染,普通变量的更新不会通知React重新渲染页面。

修改步骤:

  1. 用useState钩子替代普通变量,将array转为React状态
  2. 初始化状态时从localStorage读取数据
  3. 更新状态时使用setter函数,确保React能感知变化并触发重渲染

修改后的代码:

import "./styles.css";
import { useState, useRef } from "react";
export default function App() {
  // 函数式初始化状态,避免每次渲染重复读取localStorage
  const [array, setArray] = useState(() => {
    const notes = localStorage.getItem("notes");
    return notes !== null ? JSON.parse(notes) : [];
  });

  const Add = () => {
    const newItem = one.current.value;
    // 遵循React状态不可变原则,创建新数组而非直接修改原数组
    const newArray = [...array, newItem];
    setArray(newArray);
    localStorage.setItem("notes", JSON.stringify(newArray));
    // 清空输入框优化体验
    one.current.value = "";
  };

  const one = useRef(null);

  return (
    <>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <div className="align">
          <input ref={one} />
          <br />
          <br />
          <button onClick={Add}>Add</button>
        </div>
        <div className="align">
          {array.map((e, index) => {
            return (
              <div key={index} index={index + 1} name={e}>
                {e}
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

关键说明:

  • useState创建的状态会被React监听,调用setArray更新状态时,组件会自动重渲染,页面就能实时展示新添加的待办项
  • 函数式初始化状态只在组件首次渲染时执行一次,避免不必要的localStorage读取操作
  • React状态是不可变的,必须通过创建新数组的方式更新,不能直接调用array.push修改原数组

内容的提问来源于stack exchange,提问作者Ankit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 18:01:24