【问题标题】:Is there a good way of adding the "new" value to the array有没有一种将“新”值添加到数组的好方法
【发布时间】:2023-02-05 08:32:41
【问题描述】:
const [value, setValue] = useState(0);
const [array, setArray] = useState([1, 2]);


const handleKeyDown = (event) => {
    setValue(3);
    setArray([...array, value]);
};

在这里我希望新数组是 [1, 2, 3]

相反我得到 [1, 2, 0]

我现在知道为什么会发生这种情况,但是有什么好的方法可以解决这个问题吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    value直到下次重新渲染才会更新为3,所以调用setArray时它仍然是初始值(0)。您应该将所需的值分配给常规变量,然后将其用于两者。

    const handleKeyDown = (event) => {
        const newValue = 3;
        setValue(newValue);
        setArray([...array, newValue]);
    };
    

    【讨论】:

      【解决方案2】:

      这里的问题是值没有更新但它会变成'3'但是在下一个渲染中你可以简单地将值直接添加到数组中:

      setValue(3); // if you need to updated value for the next render
      setArray([...array, 3]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-29
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 2011-09-05
        • 2022-10-23
        • 2011-02-16
        相关资源
        最近更新 更多