简体   繁体   English

如何使用 useState hook 在 forEach 循环中设置 state

[英]How to set a state in a forEach loop using useState hook

I want to transfer data in an array A into a object B, so i doing something like [array].forEach(e => setB({...B, e})), but it seems like when traversing on later elements, former actions have been "forgotten", how should i achieve my goal?我想将数组 A 中的数据传输到 object B,所以我做了类似 [array].forEach(e => setB({...B, e})) 的操作,但似乎在遍历后面的元素时,以前的行为都被“遗忘”了,我该如何实现我的目标呢?
Prototype should looks like this:原型应如下所示:

import React from "react"
import {Map} from "immutable"

export default function App() {
    const [arrayA, setA] = React.useState([1, 2]);
    const [objB, setB] = React.useState(Map({}));
    React.useEffect(() => {
        arrayA.forEach(num => {
            setB(objB.set(num, num*num));
        })
    }, [])

    return (<div>null</div>)
}

Thanks in advance!提前致谢!

You are correct.你是对的。 With a regular value state update in a loop each subsequent enqueued update overwrites the previous update, so the last update is the one used for the next render cycle.使用循环中的常规值 state 更新,每个后续排队的更新都会覆盖先前的更新,因此最后一个更新将用于下一个渲染周期。

Solution解决方案

Normally you would use a functional state update to update from the previous state, not the state from the previous render cycle.通常,您会使用功能性 state 更新从之前的 state 更新,而不是之前渲染周期的 state。 In this case it makes more sense to map the arrayA state to an array of key-value pairs and do a single update for the objB state.在这种情况下,将 map arrayA state 转换为键值对数组arrayA state 进行一次更新objB意义。

React.useEffect(() => {
  setB(Map(arrayA.map(num => [num, num * num]));
}, []);

You're getting stale data and you should use setState callback like this:你得到的是stale data ,你应该像这样使用setState callback

export default function App() {
  const [arrayA, setA] = React.useState([1, 2]);
  const [objB, setB] = React.useState(Map({}));
  React.useEffect(() => {
    arrayA.forEach((num) => {
      setB(oldValue => oldValue.set(num, num * num));
    });
  }, []);

  return <div>null</div>;
}

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

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