React useEffect 清理功能将状态保存到数据库,而不会遇到关闭问题

问题描述 投票:0回答:1

我明白这是一个关闭问题。我的组件中的减速器中有状态,在卸载时,我想将其保存到数据库中。

const [localState, dispatch] = useReducer(myReducer, initialState);

const handleUnmount = () => {
   saveToDB(localState);
}

useEffect(() => {
  return () => {
    handleUnmount()
  }
}, [])

当组件卸载时,handleUnmount函数中的localState是陈旧的。

我尝试使用包含 localState 的依赖项数组将 handleUnmount 包装在 useCallback 中。我尝试将 localState 放入 useRef 中,并在 handleUnmount 函数中引用它,但上述方法都不起作用。此外,如果您在 useEffect 的依赖项数组中包含任何内容,则 handleUnmount 函数将在“每次”该值发生变化时运行,而不是仅在卸载时运行,这不是理想的行为。这在 React 中可能吗?我将尽一切努力不必包含“保存”按钮,必须明确单击该按钮才能保存对数据库的更改...

reactjs react-hooks closures state-saving
1个回答
1
投票

您可以使用

useRef

 来追踪该值。
const [localState, dispatch] = useReducer(myReducer, initialState); const stateRef = useRef(localState); stateRef.current = localState; useEffect(() => { return () => { saveToDB(stateRef.current); } }, [])

© www.soinside.com 2019 - 2024. All rights reserved.