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

Ana*_*kzz 5 reactjs react-native use-effect use-state

我有一个像这样的领域

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>
}
Run Code Online (Sandbox Code Playgroud)

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

[DEFAULT] while unmounting

Run Code Online (Sandbox Code Playgroud)

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

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

jea*_*182 3

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

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>
}
Run Code Online (Sandbox Code Playgroud)