johnkiller
V2EX  ›  React

React+异步任务 的疑问

  •  
  •   johnkiller · Oct 21, 2021 · 2062 views
    This topic created in 1733 days ago, the information mentioned may be changed or developed.

    背景:Vue 用户,重学 React 中

    先上代码

    function App() {
      const afterRender = () => {
        console.log('after render')
       }
    
      // 1.  渲染后回调
      // useEffect(afterRender)
      // 2.  尝试用异步方式模拟渲染后的回调
      queueMicrotask(afterRender)
      // Promise.resolve().then(afterRender)
      // setTimeout(afterRender, 0)
    
    
      return (
        <div className="App">
         <div>something</div>
        </div>
      )
    }
    

    问题在于:

    useEffect 表现正常(废话),

    而 2 中的 3 种方法,通过异步方式实现渲染后执行,afterRender 会被调用两次,即控制台打印两次after render

    这到底是什么原因?

    Supplement 1  ·  Oct 21, 2021
    已解决,react 版本 17,关掉 Strict Mode 成功解决。谢谢各位!
    5 replies    2021-10-21 14:34:56 +08:00
    mxT52CRuqR6o5
        1
    mxT52CRuqR6o5  
       Oct 21, 2021   ❤️ 1
    可能是和 fiber/concurrent mode 有关,文档中的意思也是说在最终 patch 之前可能会 render 多次
    sweetcola
        2
    sweetcola  
       Oct 21, 2021   ❤️ 1
    分析了一下,不太对劲,不应该输出两次。在 codesandbox 里调试一下,确实只输出了一次。你的 React 版本是 18 并且用上了 Strict Mode 吗(我也没用过,不太确定)?
    Kasumi20
        3
    Kasumi20  
       Oct 21, 2021
    Strict Mode
    Kasumi20
        4
    Kasumi20  
       Oct 21, 2021   ❤️ 3
    严格模式不能自动检测到你的副作用,但它可以帮助你发现它们,使它们更具确定性。通过故意重复调用以下函数来实现的该操作:

    class 组件的 constructor,render 以及 shouldComponentUpdate 方法
    class 组件的生命周期方法 getDerivedStateFromProps
    函数组件体
    状态更新函数 (即 setState 的第一个参数)
    函数组件通过使用 useState,useMemo 或者 useReducer
    Chingim
        5
    Chingim  
       Oct 21, 2021
    我用 react17/react18 都复现不了呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1331 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 23:48 · PVG 07:48 · LAX 16:48 · JFK 19:48
    ♥ Do have faith in what you're doing.