React中调用handledata函数后usersdata值未更新问题
问题原因
usersdata是普通的var变量,React不会追踪这类变量的变化。修改它的值时,组件不会触发重渲染,所以页面上显示的始终是初始值。
解决方案
React中只有通过状态管理API(如useState、useReducer)管理的数据,修改时才会触发组件重渲染,同步更新页面内容。这里提供两种修复方案:
方案1:用useState管理usersdata
把usersdata改成React状态,通过setState方法更新,确保修改能触发重渲染:
import { useEffect, useReducer, useState } from "react"; export default function Reducer() { // 用useState替代普通变量,让React追踪变化 const [usersdata, setUsersdata] = useState("jjhjhj"); const initstate = { users: [], }; const reducer = (state, action) => { if (action.type === "fetchdata") { return { users: action.data }; } else { return state; } }; const [state, dispatch] = useReducer(reducer, initstate); useEffect(() => { fetch("https://jsonplaceholder.org/users") .then((res) => res.json()) .then((data) => { dispatch({ type: "fetchdata", data: data }); }); }, []); const handledata = () => { const newContent = state.users.length // 给生成的元素添加key属性,符合React规范 ? state.users.map((user, index) => <h3 key={index}>{user.firstname}</h3>) : "Nothing to Return"; // 调用set方法更新状态,触发重渲染 setUsersdata(newContent); }; return ( <> <button className="btn btn-success" onClick={handledata}> Fetch Data </button> <br /> {usersdata} </> ); }
方案2:直接基于state.users渲染(更简洁)
既然数据已经通过useReducer管理,完全可以跳过额外变量,直接在渲染阶段根据state.users生成内容,省去按钮触发的步骤:
import { useEffect, useReducer } from "react"; export default function Reducer() { const initstate = { users: [], }; const reducer = (state, action) => { if (action.type === "fetchdata") { return { users: action.data }; } else { return state; } }; const [state, dispatch] = useReducer(reducer, initstate); useEffect(() => { fetch("https://jsonplaceholder.org/users") .then((res) => res.json()) .then((data) => { dispatch({ type: "fetchdata", data: data }); }); }, []); return ( <> <div> {state.users.length ? ( // 用用户id作为key,比索引更稳定 state.users.map((user) => <h3 key={user.id}>{user.firstname}</h3>) ) : ( "Nothing to Return" )} </div> </> ); }
内容的提问来源于stack exchange,提问作者عبدالرحمن محمد
相关产品推荐
相关产品推荐

