useState() 在循环中使用时未更新。

huangapple go评论61阅读模式
英文:

useState() not updated when state is used in a loop

问题

这段代码是我修改数据的地方,我在其中将“checked”更新为“true”或“false”。这段代码有效,因为当我使用console.log()时,它会更新状态。

setRolesData((prevState) => {
    const newState = Array.from(prevState);
    newState[targetCb]["checked"] = e.target.checked;
    return newState;
});
console.log(rolesData);

结果的图像:
useState() 在循环中使用时未更新。

这段代码是我遍历更新的数据的地方,但问题是如果尝试第二次,它不会返回与日志数据相同的数据。

// 获取所有选中的角色
const roleArr: any = [];
rolesData.map((item, index) => {
    console.log(item.checked + " ^ " + item.name);
});

结果的图像:
useState() 在循环中使用时未更新。

英文:

This code is where I modified the data, wherein I update the "checked" to whether "true" or "false". and this code works because when I console.log() it it updates the state.

    setRolesData((prevState) => {
        const newState = Array.from(prevState);
        newState[targetCb]["checked"] = e.target.checked;
        return newState;
    });
    console.log(rolesData);

Image of the result:
useState() 在循环中使用时未更新。

This code is where I loop thru the data that is updated, but the problem is it doesnt return the same data as the log data if tried for the second time.

    // get all checked roles
    const roleArr: any = [];
    rolesData.map((item, index) => {

        console.log(item.checked + " ^ " + item.name);

    });

Image of the Result:
useState() 在循环中使用时未更新。

答案1

得分: 0

所以问题在于状态没有立即更新。我将循环转移到一个方法中,在这个方法中处理表单的提交。

英文:

So the problem is that the state is not updating immediately. I transferred the loop to a method wherein it handles the submission of the form.

答案2

得分: 0

在React中,组件的生命周期是围绕着保持状态的思想构建的。当您在组件中更新一个值时,实际上会触发该组件的重新渲染。因此,如果您在组件顶部有一个带有特定值的变量,并尝试在函数内部更新此值,您会发现该值被重置。React会替换组件,包括其中的JavaScript变量。

为了保留任何变量,我们使用useState来在重新渲染之间保持组件的状态。然而,在函数中,使用useState不会立即将值保存到状态中。useState是发送给React的指令,告诉它当组件重新渲染时,我们需要保存该值。如果在重新渲染开始之前尝试访问状态中的值,您将使用“先前”的值。在您的情况下,只有在调用函数完成之后,组件才会重新渲染。

那么如何监听变化呢?

UseEffect是一个特殊的钩子,它接受一个依赖项数组作为“监听器”。当我们使用useEffect并将其作为依赖项传递一个状态值时,它告诉它在该值发生变化时运行useEffect内部的代码。

useEffect(() => {

    rolesData.map((item, index) => {
      console.log(item.checked + " ^ " + item.name);
    });

}, [rolesData]);

这段代码将在myState发生变化时运行,包括在组件初始化时。因此,我们可以使用useEffect来处理需要使用新更新的有状态值的逻辑。

英文:

In React, components have a lifecycle that is based around the idea of preserving state. When you update a value in a component we effectively trigger a re-render of the component. So if you have a variable at the top of your component with a certain value and try to update this value inside a function, you'll find that this value gets reset. React is replacing the component including the JavaScript variables inside it.

In order to preserve any variables we use useState to persist the state of the component between re-renders. However, in a function, using useState does not save the value to state immediately. useState is an instruction that is sent to React that tells it that when the component re-renders, we need to save that value. If you try to access the value in state before your re-render has begun you will be using the "previous" value instead. In your case, your component will not re-render until the calling function has been completed.

So how do you listen for changes?

UseEffect is a special hook that takes an array of dependencies as "listeners". When we use useEffect and give it a value in state as a dependency, it's telling it to run the code inside the useEffect if there is a mutation to that value.

useEffect(() => {

    rolesData.map((item, index) => {
      console.log(item.checked + " ^ " + item.name);
    });

}, [rolesData]);

This code will run every time myState is changed, including on component initialisation. So we can use useEffect to process logic that requires the newly updated stateful values.

答案3

得分: -2

UseState是异步的。所以,在循环中不会按预期工作。更好的方法是使用一些全局变量,然后根据它来更新你的状态。

英文:

UseState is asynchronous. So, it will not work in a loop as expected. The better approach would be to use some gloabl variable and later update your state based on it.

huangapple
  • 本文由 发表于 2023年6月2日 14:49:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定