【问题标题】:access useState variable in cleanup/return method of useEffect在 useEffect 的清理/返回方法中访问 useState 变量
【发布时间】:2021-06-06 18:30:15
【问题描述】:

我有一个这样的字段

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

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

【问题讨论】:

  • 请研究更多关于 Hooks 依赖的信息。在我看来,这就是问题所在。 reactjs.org/docs/…
  • title 添加到该钩子的依赖项中。这应该告诉 React 在 title 更改时运行此 useEffect
  • 由于“陈旧关闭”而显示初始值。相关:stackoverflow.com/a/66435915/2873538

标签: reactjs react-native use-effect use-state


【解决方案1】:

你需要在钩子的依赖数组中添加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>
}

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2020-03-19
    • 2021-11-17
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多