使用依赖项卸载时的 useEffect 清理

Mit*_*dge 5 reactjs react-hooks

我需要一种仅在组件卸载时运行 React useEffect 清理函数的方法,但使用组件的最新状态。

考虑以下示例:

const [foo, setFoo] = useState(true)

useEffect(() => {
  return () => {
    if(foo) 
      console.log("T") 
    else
      console.log("F")
  }
}, [])

...later:

setFoo(false)
Run Code Online (Sandbox Code Playgroud)

foo在此示例中,即使当前值为,也会在卸载时打印“T” false

您的第一个想法可能是添加foo到效果的依赖数组中,但这会导致效果清理两次:一次当状态更改为false(打印“T”)时,一次当组件卸载时(打印“F”) 。

我希望它只在组件卸载后打印“F”。

Mit*_*dge 6

该问题的一种解决方案是使用useRef如下:

const [foo, setFoo] = useState(true)

// Store value of foo and keep it up-to-date.
const fooRef = useRef(foo)
useEffect(() => fooRef.current = foo, [foo]);

// Use ref value.
useEffect(() => {
  return () => {
    if(fooRef.current) 
      console.log("T") 
    else
      console.log("F")
  }
}, [])

...

setFoo(false)
Run Code Online (Sandbox Code Playgroud)