ethusdt
0.01D
V2EX  ›  React

为什么 react 中 effect cleanup 是在每次 re-render 之后再调用?

  •  
  •   ethusdt · Feb 23, 2022 · 3399 views
    This topic created in 1714 days ago, the information mentioned may be changed or developed.
    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 之后调用.

    7 replies  •  2022-02-23 19:47:23 +08:00
    noe132
    noe132
    Feb 23, 2022❤️1
    1
    你把 useEffect 理解成这样的模型就可以了。
    useEffect = (effect) => {
    if (clearUp) {
    clearUp()
    }
    clearUp = effect()
    }
    86co
    86co
    Feb 23, 2022
    3
    因为是 componentDidUpdate 啊
    XTTX
    XTTX
    Feb 23, 2022
    4
    &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])

    ```
    charlie21
    charlie21
    Feb 23, 2022
    6
    useEffect 里面既能看到当前 render 的值,也能看到上一次 render 的值
    https://overreacted.io/zh-hans/a-complete-guide-to-useeffect/

    React 能做到在绘制后立即处理 effects — 并且默认情况下使你的应用运行更流畅。如果你的代码需要依然可以访问到老的 props

    所以这篇文章给出的答案是 “使你的应用运行更流畅”,即使 cleanup 里面卡到了,它不会卡到 UI 渲染
    ethusdt
    ethusdt
    OP
    Feb 23, 2022
    7
    @charlie21 嗯, 应该是这样的, UI 渲染第一位.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1315 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 20:39 · PVG 04:39 · LAX 12:39 · JFK 15:39
    ♥ Do have faith in what you're doing.