首页 > 解决方案 > 使用反应钩子useState更新功能的正确方法是什么?

问题描述

考虑以下声明:

   const [stateObject, setObjectState] = useState({
      firstKey: '',
      secondKey: '',
    });

以下片段是否都正确?

一个)

setObjectState((prevState) => ({
  ...prevState,
  secondKey: 'value',
}));

二)

setObjectState({
  ...stateObject,
  secondKey: 'value',
}));

我确信 A) 是正确的,但有必要吗?B) 看起来不错,但由于 setObjectState 是一个异步函数,因此 stateObject 可能没有最新的值。

标签: reactjsreact-hooks

解决方案


A 将始终为您提供更新的值。B可能是正确的,但可能不是。让我举个例子:

const Example = props => {
    const [counter, setCounter] = useState(0);

    useEffect(() => {
        // 0 + 1
        // In this first case the passed value would be the same as using the callback.
        // This is because in this cycle nothing has updated counter before this point.
        setCounter(counter + 1);

        // 1 + 1
        // Thanks to the callback we can get the current value
        // which after the previous iexample is 1.
        setCounter(latest_value => latest_value + 1);

        // 0 + 1
        // In this case the value will be undesired as it is using the initial
        // counter value which was 0.
        setCounter(counter + 1);
    }, []);

    return null;
};

当新值取决于更新的值时,请使用回调,否则您可以简单地传递新值。

const Example = props => {
    const [hero, setHero] = useState('Spiderman');

    useEffect(() => {
        // Fine to set the value directly as
        // the new value does not depend on the previous one.
        setHero('Batman');

        // Using the callback here is not necessary.
        setHero(previous_hero => 'Superman');
    }, []);

    return null;
};

同样在您给出的示例中,使用两种不同的状态可能会更好:

const [firstKey, setFirstKey] = useState("");
const [secondKey, setSecondKey] = useState("");

推荐阅读