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重新渲染页面。
修改步骤:
- 用
useState钩子替代普通变量,将array转为React状态 - 初始化状态时从localStorage读取数据
- 更新状态时使用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
相关产品推荐
相关产品推荐

