简体   繁体   English

React hooks 在 useEffect 的清理函数中丢失了状态变量的更新值

[英]React hooks loses updated value of state variable inside cleanup function of useEffect

I have this useEffect hook which does something on componentDidMount and want to use it in the end to update my redux store at componentWillUnMount .我有这个 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 })
    }
}, [])

As mentioned in code snippet, ordersToCancel get reset in cleanup function.正如代码片段中提到的, ordersToCancel在清理函数中被重置。 I'm making sure this is getting updated.我确保这会得到更新。 I have another useEffect hook with dependency of ordersToCancel and I can see its getting called and updating the array.我有另一个useEffect钩子,它依赖于ordersToCancel ,我可以看到它被调用并更新数组。

Is it the normal behavior that the state will get reset to default in cleanup function?状态将在清理功能中重置为默认值是正常行为吗?

You can use useRef to keep an indirect reference to the ordersToCancel variable:您可以使用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 })
    }
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM