我有一个这样的字段
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。
如何在组件卸载时捕获更改?
发布于 2021-03-09 05:17:08
您需要在钩子的依赖项数组中添加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>
}https://stackoverflow.com/questions/66537217
复制相似问题