1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        [譯] 為何 React 18 中 useEffect 會(huì)運(yùn)行兩次?

        共 1000字,需瀏覽 2分鐘

         ·

        2022-06-07 00:20


        原文:https://flaviocopes.com/react-useeffect-two-times/

        在 2022 年 3 月發(fā)布的 React 18 的發(fā)布公告中,數(shù)量可觀的新特性撲面而來(lái)。而對(duì) useEffect() 的默認(rèn)行為的改變,可能就此被淹沒了。

        如果你的應(yīng)用在更新到 React 18 之后行為迥異,或許正是因?yàn)?useEffect() 默認(rèn)變?yōu)楸贿\(yùn)行 2 次了

        雖然這種情況只發(fā)生在 development mode 中,但無(wú)疑每位開發(fā)者都會(huì)遇到。

        另一個(gè)限制條件是 只在 strict mode 發(fā)生,但這同樣是用 create-react-app 或 Next.js 所構(gòu)建應(yīng)用的默認(rèn)選項(xiàng)。

        事情就是這么個(gè)事情,所以不用緊張是不是代碼出了什么問題 -- React 的現(xiàn)狀如此。

        唯一避免這種行為的方法就是 禁用 strict mode;鑒于嚴(yán)格模式的重要性,這畢竟是個(gè)你能修復(fù)這種改變引入的任何問題之前臨時(shí)的變通之策。

        在 Next.js 中,可以在 next.config.js 文件里增加這個(gè)選項(xiàng):

        reactStrictMode:?false

        create-react-app 創(chuàng)建的應(yīng)用里,可以把 index.js 文件里的 StrictMode 高階組件去除:

        比如從這樣:

        import?React,?{?StrictMode?}?from?'react';
        import?{?createRoot?}?from?'react-dom/client';

        import?App?from?'./App';

        const?rootElement?=?document.getElementById('root');
        const?root?=?createRoot(rootElement);

        root.render(
        ??<StrictMode>
        ????<App?/>
        ??StrictMode>

        );

        改為:

        import?React?from?'react';
        import?{?createRoot?}?from?'react-dom/client';

        import?App?from?'./App';

        const?rootElement?=?document.getElementById('root');
        const?root?=?createRoot(rootElement);

        root.render(
        ??<App?/>
        );




        瀏覽 115
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            人性动zzzz0000xxxx | 欧美韩日精品电影网 | 主妇的呻吟hd中字电影 | 亚洲手机在线观看 | 免费在线观看黄色片 | 豆花天天吃最新视频 | 大香蕉伊人电影 | 成人做爰无码A片韩国电影网斗生 | 国产在线成人视频 | 亚洲精品456在线播放app |