function Detail() {
const x = Math.random();
console.log('render: ', x);
React.useEffect(() => {
console.log('effect: ', x);
return function() {
console.log('cleanup: ', x);
}
})
const [, forceUpdate] = React.useReducer(x=>x+1,0);
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Detail!</Text>
<Button title="forceupdate" onPress={forceUpdate} />
</View>
);
}
页面进入-点击 forceupdate 按钮, 点击返回按钮页面结束, 日志:
render: 0.5817026745695149
effect: 0.5817026745695149
render: 0.7876494718531499
cleanup: 0.5817026745695149
effect: 0.7876494718531499
cleanup: 0.7876494718531499
实际上:
Mount -> Update -> Re-render -> cleanup -> Unmount -> cleanup
为什么不是:
Mount -> Update -> cleanup -> Re-render -> Unmount -> cleanup
React 官网的介绍:
When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
虽然说了 cleanup 是在下一次 effect 之前调用, 但也没有讲为什么是在下一次 render 之后调用.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.