在 useEffect 的 cleanup/return 方法中访问 useState 变量

access useState variable in cleanup/return method of useEffect

我有这样一个字段

const SimpleReactComponent = (props) => {
  const [title, setTitle] = useState('DEFAULT')

  useEffect(() => {
    return () => {
      // unmount 
      console.log(`[${title}] while unmounting`)
    }
  }, [])
  return <TextInput value={title} onChangeText={title => setTitle(title)}></TextInput>
}

当我修改 title 字段并离开该组件时,它仍然打印以下内容

[DEFAULT] while unmounting

虽然我期待新修改的值而不是 DEFAULT

如何在卸载组件时捕获更改?

您需要在钩子的依赖数组中添加标题值。如果不是,挂钩只会在组件安装时 运行 并记录当时的初始值。 在依赖数组中添加 title 将使 useEffect 在每次 title 值更改时监听,并且在您卸载组件时它会显示正确的值。

const SimpleReactComponent = (props) => {
  const [title, setTitle] = useState('DEFAULT')

  useEffect(() => {
    return () => {
      // unmount 
      console.log(`[${title}] while unmounting`)
    }
  }, [title])
  // Dependency array need the title to run everytime the value changes and when the unmount runs it will have the latest value!

  return <TextInput value={title} onChangeText={title => setTitle(title)}></TextInput>
}