为什么useState不触发重新渲染? [英] Why is useState not triggering re-render?

查看:1663
本文介绍了为什么useState不触发重新渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经初始化了一个数组状态,当我更新它时,我的组件不会重新渲染.这是一个最小的概念证明:

I've initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:

function App() {
  const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
  console.log("rendering...");
  return (
    <div className="App">
      {numbers.map(number => (
        <p>{number}</p>
      ))}
      <input
        type="text"
        value={numbers[0].toString()}
        onChange={newText => {
          let old = numbers;
          old[0] = 1;
          setNumbers(old);
        }}
      />
    </div>
  );
}

根据此代码,似乎输入应包含要开始的数字0,并且每当更改它时,状态也应该更改.输入"02"后,在输入中,App组件不会重新呈现.但是,如果我在5秒钟后执行的onChange函数中添加setTimeout,则表明数字确实已更新.

Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering "02" in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.

关于组件为什么不更新的任何想法?

Any thoughts on why the component doesn't update?

这是带有概念证明的 CodeSandbox .

推荐答案

您正在调用setNumbers并将其已拥有的数组传递给它.您已经更改了它的值之一,但是它仍然是相同的数组,我怀疑React并没有看到任何重新渲染的理由,因为状态没有改变.新数组是旧数组.

You're calling setNumbers and passing it the array it already has. You've changed one of its values but it's still the same array, and I suspect React doesn't see any reason to re-render because state hasn't changed; the new array is the old array.

避免这种情况的一种简单方法是将数组散布到新数组中:

One easy way to avoid this is by spreading the array into a new array:

setNumbers([...old])

这篇关于为什么useState不触发重新渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆