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

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

如何在组件卸载时捕获变化?

最佳答案

你需要在钩子(Hook)的依赖数组中添加标题值。如果不是, Hook 将仅在组件安装时运行,并记录当时的初始值。 在依赖项数组中添加 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>
}

关于reactjs - 在 useEffect 的清理/返回方法中访问 useState 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66537217/

相关文章:

javascript - 对 useEffect Hook 内的多个 setState() 调用进行 React 批量更新

javascript - 从 Prop React JS 返回对象数组

javascript - 如何在 native react 中从数组中删除重复项

javascript - React Native FlatList 在添加新数据时重新渲染已经渲染的项目

css - 为什么我的子容器在我的 react native 应用程序中有填充时,我的子容器占据全宽?

javascript - React,在渲染组件之前从数据库获取数据

reactjs - 如何在 useEffect 中使用 setTimeout 重置 React 钩子(Hook)状态

node.js - 仍使用IE显示页面上不存在的旧数据

javascript - 将值传递给捆绑的 React JS 文件?

android apk 突然运行和关机