[英]When using useState hook - Is there an importance to changing the setState functions call order?
I have a React functional component with two state variables ( itemsData
& itemsCollections
). 我有一个带有两个状态变量(
itemsData
和itemsCollections
)的React功能组件。 The variables are updated in the useEffect
method. 变量在
useEffect
方法中更新。 But after useEffect
occur one of the state variables is null
. 但是在
useEffect
发生后,状态变量之一为null
。
Upon switching the setStateFunctions ( setItemsData
& setItemsCollect
) call order both arguments are inialized as expected. 切换setStateFunctions(
setItemsData
& setItemsCollect
)调用顺序后,两个参数均按预期初始化。
How's that? 怎么样?
const MyComponent = ({itemsIds}) => {
const [itemsData, setItemsData] = useState([]);
const [itemsCollections, setItemsCollect] = useState({});
useEffect(() => {
fetchItemsData({ itemsIds }).then(({ items, itemCollect }) => {
setItemsData(items);
setItemsCollect(itemCollect);
})
}, [itemsIds]);
...
console.log('itemsData', itemsData) // the expected array
console.log('itemCollect', itemCollect) // empty objecy
State after useEffect: itemCollect = {}, itemsData = [{value:...},...]
useEffect之后的状态:
itemCollect = {}, itemsData = [{value:...},...]
Switching the order of the calls: 切换通话顺序:
const MyComponent = ({itemsIds}) => {
...
useEffect(() => {
fetchItemsData({ itemsIds }).then(({ items, itemCollect }) => {
setItemsCollect(itemCollect); // <--> switched rows
setItemsData(items); // <--> switched rows
})
}, [itemsIds]);
...
console.log('itemsData', itemsData) // the expected array
console.log('itemCollect', itemCollect) // the expected object
State after useEffect: itemCollect = { someValue: ...} , itemsData = [{value:...},...]
useEffect之后的状态:
itemCollect = { someValue: ...} , itemsData = [{value:...},...]
There is a performance optimization called batching, which can change between React versions . 有一个称为批处理的性能优化, 可以在React版本之间进行更改 。 When this optimization is applied, multiple
setState
calls will be batched together before the next render (and the order does not matter). 应用此优化后,将在下一次渲染之前将多个
setState
调用分批处理(顺序无关紧要)。
When not applied (eg inside a Promise as in your case, see Does React batch state update functions when using hooks? ), then each state update will trigger a new render (and the order matters). 如果不应用(例如,在您的情况下,在Promise中,请参阅使用钩子时React批处理状态是否更新功能? ),则每次状态更新都会触发一个新的渲染(顺序很重要)。
=> console.log('itemCollect', itemCollect)
may log different data in each render. =>
console.log('itemCollect', itemCollect)
可能会在每个渲染器中记录不同的数据。
If you need to force a single state update, then calling a single dispatch from useReducer might be the best option. 如果您需要强制进行单个状态更新,那么从useReducer调用单个调度可能是最好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.