我有一个这样的字段
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/