我有这个useEffect钩子,它在componentDidMount
上执行了某些操作,并希望最后使用它来更新componentWillUnMount
上的redux存储。
const [ordersToCancel, dispatchCancelStatus] = useReducer(cancelReducer, []);
const cancelReducer = (state, action) => {
//implementation
}
useEffect(()=>{
//some Code
dispatchCancelStatus({ type: "type", state: state });
return async ()=> {
const data = ordersToCancel //ordersToCancel is an empty array here as it's default value not the updated one
//some code
const results = await api({params})
dispatch({ type: 'someType', data: data })
}
}, [])
如代码片段所述,ordersToCancel
在清除功能中被重置。我确定这正在更新。我还有另一个useEffect
依赖项的ordersToCancel
钩子,可以看到它被调用并更新了数组。
在清除功能中将状态重置为默认值是正常现象吗?
答案 0 :(得分:1)
您可以使用useRef
来间接引用ordersToCancel
变量:
const [ordersToCancel, dispatchCancelStatus] = useReducer(cancelReducer, []);
const ordersToCancelRef = useRef();
ordersToCancelRef.current = ordersToCancel;
const cancelReducer = (state, action) => {
//implementation
}
useEffect(()=>{
//some Code
dispatchCancelStatus({ type: "type", state: state });
return async ()=> {
const data = ordersToCancelRef.current;
//some code
const results = await api({params})
dispatch({ type: 'someType', data: data })
}
}, [])