简体   繁体   English

使用 useState 挂钩时反应 state 未正确更新

[英]React state not updated correctly when using useState hook

I have this example code.我有这个示例代码。 I have a state urls which I create using useState hook.我有一个使用 useState 钩子创建的 state 网址。 I have initialized urls state to empty array.我已将 URL state 初始化为空数组。 I have another array arr.我有另一个数组 arr。 For each item in arr, I am pushing that item to urls state.对于 arr 中的每个项目,我将该项目推送到 urls state。 When I render contents of urls, only last item pushed is displayed.当我渲染 url 的内容时,只显示最后一个推送的项目。 It seems while updating urls, only last update is taking effect.似乎在更新 url 时,只有最后一次更新才生效。 What could be wrong?有什么问题?

function Hi() {
  const [urls, setUrls] = useState([]);

  let arr = ["hi", "hello"];

  React.useEffect(() => {

    arr.forEach(item => {
      let url_list = [...urls];
      url_list.push(item);
      setUrls(url_list)
    })

  }, []);

  return (
    <div>
     {urls.map(item => (
        <Text>{item}</Text>
     ))}
    </div>
  )
}

You're updating the state in each interaction of the array.您正在阵列的每次交互中更新 state。

The problem here is that setState is asynchronous ( read ), ie the update doesn't happen instantly.这里的问题是 setState 是异步的( read ),即更新不会立即发生。 In other words, when you do let url_list = [...urls] , on the second and last iteraction, urls is still [], so that's why you're only getting "hello" into it.换句话说,当您执行let url_list = [...urls]时,在第二次也是最后一次迭代中,urls 仍然是 [],所以这就是为什么您只会在其中输入“hello”。

You have 2 main approachs in this case:在这种情况下,您有两种主要方法:

1. Update the state after you've mapped the entire array. 1. 映射整个阵列后更新 state。

React.useEffect(() => { 
  let url_list = [...urls]

  arr.forEach(item => {
    url_list.push(item);
  })

  setUrls(url_list)

}, []);

2. Since setState returns the previous state ( read ), you can do something like this: 2. 由于 setState 返回之前的 state ( read ),你可以这样做:

React.useEffect(() => {
   
  arr.forEach(item => {
    let url_list = [...urls];
    url_list.push(item);
    setUrls(prevUrls => ([...prevUrls, ...url_list]))
  })
        
}, []);

You are defining url_list inside forEach.您在 forEach 中定义url_list This is reset the values inside url_list on each iterations.这是在每次迭代时重置 url_list 中的值。 Declare url_list outside of forEach and it should be working在 forEach 之外声明 url_list 它应该可以工作

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

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