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

时间:2020-10-13 15:05:50

标签: reactjs react-hooks

我有这个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钩子,可以看到它被调用并更新了数组。

在清除功能中将状态重置为默认值是正常现象吗?

1 个答案:

答案 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 })
    }
}, [])