You need to enable JavaScript to run this app. React状态更新后未触发重渲染:列表排序后DOM不更新问题
优惠活动
大模型
产品
解决方案
定价
更多

React状态更新后未触发重渲染:列表排序后DOM不更新问题

问题原因

Array.prototype.sort() 是原地排序方法,会直接修改调用它的原数组,最终返回的也是原数组的引用。你直接对state里的items调用sort方法,排序后拿到的sortItems和原来的items是同一个数组引用,React做状态更新的浅比较时会认为状态没有发生变化,因此不会触发组件重新渲染,自然也就不会更新DOM内容。

修复方案

你只需要在排序前先对原数组做一次浅拷贝,基于拷贝后的数组做排序即可,修改handleSort的实现如下:

const handleSort = () => {
  // 先浅拷贝原数组,生成新的数组引用
  const sortedItems = [...items].sort((a, b) => {
    const nameA = a.name.toUpperCase();
    const nameB = b.name.toUpperCase();
    if(nameA < nameB) return -1;
    if(nameA > nameB) return 1;
    return 0;
  });
  setItems(sortedItems);
}

你也可以用Array.from(items)等其他浅拷贝方式代替扩展运算符,只要保证传给setItems的是新的数组引用,React就能检测到状态变化触发重渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:45:03