React点击按钮状态更新但页面不渲染,添加Link无效果求助
问题:点击按钮添加新链接但组件未更新
我希望每次点击按钮时添加新的链接,代码实现如下:
初始State设置
const [links, setLinks] = useState([ { number: 1, platforms: null, url: null, }, ]);
点击事件处理函数
const handleclick = () => { let addLinks = links; const newLink = { number: links.length + 1, platforms: null, url: null, }; addLinks.push(newLink); return setLinks(addLinks); };
渲染代码
<h1>Customize your links</h1> <p> Add/Edit/Remove links and then share all your profiles with the world </p> <button type="button" class="btn btn-outline-danger " style={{ border: "1px solid #a009e4", color: "#a009e4" }} onClick={handleclick} > + Add New Link </button> {links.map((link)=>{ return ( <AllLinks number={link.number} key={link.number}/> ); })}
当前问题
点击按钮后state(links)的值已改变,但浏览器未添加新链接,尝试使用useEffect后问题仍存在。
问题原因
你直接修改了原state数组的引用——let addLinks = links;只是把原数组的内存地址赋值给了新变量,push操作是在原数组上直接修改。React的state更新依赖引用变化触发重新渲染,因为原数组引用没变,所以组件不会更新。
解决方法
创建原数组的副本,在副本上添加新元素后再传给setLinks,以下是几种可行方案:
方案1:使用扩展运算符创建新数组
const handleclick = () => { const newLink = { number: links.length + 1, platforms: null, url: null, }; setLinks([...links, newLink]); };
方案2:使用Array.concat()生成新数组
const handleclick = () => { const newLink = { number: links.length + 1, platforms: null, url: null, }; setLinks(links.concat(newLink)); };
方案3:函数式更新(推荐,避免闭包问题)
如果更新逻辑依赖前一次的state状态,使用函数式更新能确保拿到最新的state值:
const handleclick = () => { setLinks(prevLinks => { const newLink = { number: prevLinks.length + 1, platforms: null, url: null, }; return [...prevLinks, newLink]; }); };
修改后每次点击都会生成新的数组引用,React会检测到state变化并触发组件重新渲染,新链接就能正常显示了。
内容的提问来源于stack exchange,提问作者dhia mlayah
相关产品推荐
相关产品推荐

