reactjs - 使用反应钩子useState更新功能的正确方法是什么?
问题描述
考虑以下声明:
const [stateObject, setObjectState] = useState({
firstKey: '',
secondKey: '',
});
以下片段是否都正确?
一个)
setObjectState((prevState) => ({
...prevState,
secondKey: 'value',
}));
二)
setObjectState({
...stateObject,
secondKey: 'value',
}));
我确信 A) 是正确的,但有必要吗?B) 看起来不错,但由于 setObjectState 是一个异步函数,因此 stateObject 可能没有最新的值。
解决方案
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("");
推荐阅读
- c++ - 如何在 cpp 中将字符串(Thu Oct 3 18:45:10 2019)转换为 time_t 格式?
- android - 跨 React Native 和 Android 的 AWS Amplify 身份验证
- python - 在 asyncio 中并行化 for 循环
- machine-learning - 词嵌入模型
- php - 如何在 php 代码中为 google 客户端发送referer?
- prestashop-1.7 - 在后台 prestashop 1.7 中保存产品后需要重新加载
- node.js - 在 NodeJS 中表达;如何从表单帖子中获取表单属性?
- jenkins - jenkins json中的树查询参数返回400错误
- angular - 角度或http客户端正确错误中的网络检测
- django - 在视图中定义函数