你不知道的React系列(三十八)StrictMode

66 阅读1分钟

本文正在参加「金石计划」

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

const root = createRoot(document.getElementById('root'));
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

StrictMode 不会渲染任何可见的 UI,触发额外的检查和警告

  • 组件重新渲染发现不纯的渲染

    Encountered two children with the same key

    Strict 会执行以下动作

    • 组件函数
    • 传给 useState 的函数, set functions, useMemo, or useReducer
    • class 组件 constructor, render, shouldComponentUpdate
  • 组件重新运行 Effect 发现错误的 cleanup

    重新运行 cleanup 和 setup 函数

    cleanup 函数有问题 Effect 就会执行多次崩溃

  • 组件检查过时的 API

    • findDOMNode
    • UNSAFE_ 生命周期
    • context 方法 (childContextTypes, contextTypes, and getChildContext)
    • refs (this.refs)
  • 整个应用使用

  • 部分使用

    import { StrictMode } from 'react';
    
    function App() {
      return (
        <>
          <Header />
          <StrictMode>
            <main>
              <Sidebar />
              <Content />
            </main>
          </StrictMode>
          <Footer />
        </>
      );
    }