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 之后调用.