【问题标题】:React does not re-render updated array stateReact 不会重新渲染更新的数组状态
【发布时间】:2020-09-05 20:23:35
【问题描述】:

我在下面有一个简单的数组,我只是通过处理程序更改数组中元素的索引:

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

我的处理程序:

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);
};

我尝试如下渲染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>

现在,我的数组已正确更改并更新状态,但不会重新渲染。

这是我在 CodeSandBox 中的项目演示:Link

【问题讨论】:

    标签: javascript arrays reactjs state


    【解决方案1】:

    这是因为items数组的实例没有改变。

    试试这个:

    setItems([...items]);
    

    这会将数组复制到一个新的相同数组。 React 会发现它有所不同并会重新渲染。

    【讨论】:

    • 非常有帮助。谢谢!
    • 我被困了 4 个小时。谢谢
    • 我现在明白了...
    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多