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 之后调用.
1
noe132 2022-02-23 12:39:14 +08:00 1
你把 useEffect 理解成这样的模型就可以了。
useEffect = (effect) => { if (clearUp) { clearUp() } clearUp = effect() } |
2
bojackhorseman 2022-02-23 13:15:23 +08:00 via iPhone 1
|
3
86co 2022-02-23 13:39:00 +08:00
因为是 componentDidUpdate 啊
|
4
XTTX 2022-02-23 13:56:24 +08:00
&t=806s
这里解释得清楚。 你的代码有点绕,正常情况下 useEffect 要带 dependencies. ``` const [change, SetChange] = React.useState(false) useEffect(() => { console.log('fetch') let isCancelled = false setTimeout(() => { if (!isCancelled) { console.log('first') } }, 1000) return () => { isCancelled = true } }, [change]) ``` |
5
xzh654321 2022-02-23 16:18:53 +08:00
写 useEffect 的时候要把 dependencies 写进去.
参考: https://overreacted.io/zh-hans/a-complete-guide-to-useeffect/ https://www.zhihu.com/question/508780830/answer/2290031407 |
6
charlie21 2022-02-23 19:09:25 +08:00
useEffect 里面既能看到当前 render 的值,也能看到上一次 render 的值
https://overreacted.io/zh-hans/a-complete-guide-to-useeffect/ React 能做到在绘制后立即处理 effects — 并且默认情况下使你的应用运行更流畅。如果你的代码需要依然可以访问到老的 props 所以这篇文章给出的答案是 “使你的应用运行更流畅”,即使 cleanup 里面卡到了,它不会卡到 UI 渲染 |