简体   繁体   English

React 不会重新渲染更新后的数组 state

[英]React does not re-render updated array state

I have a simple array in below and I just change index of elements in array by a handler:我在下面有一个简单的数组,我只是通过处理程序更改数组中元素的索引:

const [items, setItems] = useState([
    { id: 5, val: "Iran" },
    { id: 2, val: "Germany" },
    { id: 3, val: "Brazil" },
    { id: 4, val: "Poland" }
]);

My Handler:我的处理程序:

const handlePosition = (old_index, new_index) => {
    if (new_index >= items.length) {
      var k = new_index - items.length + 1;
      while (k--) {
        items.push(undefined);
      }
    }
    items.splice(new_index, 0, items.splice(old_index, 1)[0]);

    setItems(items);

    console.log(items);
};

I try to render the items array as follows:我尝试按如下方式呈现items数组:

<ul>
  {items.map((item, index) => (
    <li key={item.id}>
      {item.val}
      <button onClick={() => handlePosition(index, index + 1)}>🡇</button>
      <button onClick={() => handlePosition(index, index - 1)}>🡅</button>
    </li>
  ))}
</ul>

Now, My array changed properly and updates the state but not re-render.现在,我的阵列已正确更改并更新 state但不重新渲染。

Here is a demo of my project in CodeSandBox: Link这是我在 CodeSandBox 中的项目演示: 链接

It's because the instance of the items array is not changing.这是因为items数组的实例没有改变。

Try this:尝试这个:

setItems([...items]);

That copies the array to a new identical array.这会将数组复制到一个新的相同数组。 React will see that it's different and will re-render. React 会发现它不同并且会重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM