zoukankan      html  css  js  c++  java
  • 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环境下不会这样,所以不用担心

  • 相关阅读:
    css 透明气泡效果
    uniapp 跳转tabbar页面传递参数
    unaipp 发送验证码倒计时
    uniapp 返回顶部
    js 实现放大镜效果
    js 禁用右键菜单和禁止复制
    js 表格的添加和删除操作
    js 留言板(带删除功能)
    推荐几个好用的网站
    pc端使用rem适配
  • 原文地址:https://www.cnblogs.com/bobo1/p/12863088.html
Copyright © 2011-2022 走看看