React 16.13.1開啟嚴格模式會觸發兩次render


看代碼

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

  這時候組件里的render()會執行兩次

import React from 'react';
export default class About extends React.Component {
  render() {
    console.log('---about-');
    return (
      <div>
        Here is About!
        <div>
          傳過來的值:{this.props.match.params.id}
          <br/>
          中文:{this.props.match.params.text}
        </div>
      </div>
    )
  }
}

  

 

 

strict mode的通過兩次調用constructor和render函數來更好的檢測不符合預期的side effects

文檔中有表明

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

下列函數會執行兩次

  • 類組件的constructor,render和shouldComponentUpdate方法
  • 類組建的靜態方法getDerivedStateFromProps
  • 函數組件方法體
  • 狀態更新函數(setState的第一個參數)
  • 傳入useState,useMemo或useReducer的函數

在production環境下不會這樣,所以不用擔心

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM