React StrictMode 严格模式下组件生命周期连续渲染两次

前言

正在努力学习 React 框架中,在写练习 demo 时发现组件生命周期函数连续渲染两次,百思不得其解,于是各种谷歌百度,终于了解了原因,在此记录一下。

一、解决办法

先看代码:

import React from 'react'

interface PropsType {
  [key: string]: any
}
class ComTest extends React.Component {
  timer: NodeJS.Timer | null = null
  componentDidMount() {
    this.timer = setInterval(() => {
      console.log('时间控制器');
    }, 1000)
  }
  componentWillUnmount() {
    console.log('componentWillUnmount')
    clearInterval(Number(this.timer))
  }
  render(): React.ReactNode {
    return (
      <>
        <p>组件卸载测试</p>
      </>
    )
  }
}
export default class Lifecycle extends React.Component<PropsType> {
  constructor(props: PropsType) {
    super(props)
    console.log('constructor')
  }
  state = {
    count: 0,
    flag: true
  }
  componentDidMount() {
    console.log('componentDidMount')
  }
  componentDidUpdate() {
    console.log('componentDidUpdate')
  }
  
  addCount = () => {
    this.setState({
      count: this.state.count + 1
    })
  }
  unMountTest = (flag: boolean) => {
    this.setState({
      flag
    })
  }
  render(): React.ReactNode {
    console.log('render');
    return (
      <>
        生命周期
        <p>数字:{this.state.count}</p>
        <button onClick={this.addCount}>+</button>
        {this.state.flag ? <ComTest></ComTest> : null}
        <button onClick={() => this.unMountTest(false)}>卸载test</button>
        <button onClick={() => this.unMountTest(true)}>加载test</button>
      </>
    )
  }
}

如上代码,在加载页面时,发现 componentDidMount 生命周期函数连续调用两次,截图如下:

解决这个问题,只需要将 index.tsx 文件中的严格模式组件 React.StrictMode 去掉即可。

 注释之后,执行效果如下,生命周期函数只调用一次。

 二、原因

上面只是说了解决办法,这里说一下为什么。

StrictMode 是一个用来检查项目中潜在问题的工具。StrictMode 不会渲染任何可见的 UI,它为其后代元素触发额外的检查和警告。

注意:严格模式检查仅在开发模式下运行;它们不会影响生产构建。

StrictMode 目前有助于:

1、识别不安全的生命周期;
2、关于使用过时字符串 ref API 的警告;
3、关于使用废弃的 findDOMNode 方法的警告;
4、检测意外的副作用;
5、检测过时的 context API。

最后,回归到本文的问题:组件的一次更新流程,在视图真正刷新之前的部分都是可能被多次调用的,因而这些部分中不能出现副作用,开发环境下会刻意触发两次以使得开发者能注意到误用的副作用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值