在 useEffect 的清理/返回方法中访问 useState 变量

时间:2021-03-08 21:08:11

标签: 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>
}

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

[DEFAULT] while unmounting

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

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

1 个答案:

答案 0 :(得分:0)

需要在hook的依赖数组中添加title值。如果不是,钩子只会在组件挂载时运行,并在那个时候记录初始值。 在依赖数组中添加 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>
}