一段很普通的代码,出发了两次render

import React, { useState, useEffect } from 'react'

const MouseTracker: React.FC = () => {
const [ positions, setPositions ] = useState({x: 0, y: 0})
useEffect(() => {
console.log('add effect', positions.x)
const updateMouse= (e: MouseEvent) => {
console.log('inner')
setPositions({ x: e.clientX, y: e.clientY })
}
document.addEventListener('click', updateMouse)
return () => {
console.log('remove effect', positions.x)
document.removeEventListener('click', updateMouse)
}
},[])
console.log('before render', positions.x) // 执行了两次
return (
<>
<p>X: {positions.x}, Y : {positions.y}</p>
</>
)
} export default MouseTracker

原因:

最近的react版本,dev模式下render使用的是strict mode,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环境下不会这样,所以不用担心

最新文章

  1. html5标签知多少
  2. 【原】ZenCoding中常用的CSS3样式
  3. angular的splitter案例学习
  4. HDU 5002 Tree LCT 区间更新
  5. 从运维角度浅谈 MySQL 数据库优化
  6. 原代码,反码,解释和具体的补充 Java在&amp;gt;&amp;gt;和&amp;gt;&amp;gt;&amp;gt;差异
  7. Java课程设计——GUI密码生成器201521123035
  8. Indent Guides for Visual Studio 代码格式化收缩插件
  9. Laravel5笔记--路由
  10. rem和em学习笔记及CSS预处理(未完待续)
  11. [c++] opencv加载png
  12. 苹果App Store审核指南中文翻译(更新至140227)
  13. 将n的k位清0
  14. PHP:第二章——PHP中的equire与incude语句
  15. 深入浅出-网络七层模型&amp;&amp;网络数据包
  16. insert into 的另一种添加插入新行方式
  17. 关于UI回调Invoker的实现(一)
  18. dubbo异步调用三种方式
  19. IIS7日志中时间与系统时间不一致的原因
  20. (转)Cobbler自动化部署最佳实践

热门文章

  1. hdu 2176 取(m堆)石子游戏 (裸Nim)
  2. Linux 启动/关闭 oracle 数据库
  3. Mysql多实例搭建部署
  4. IDEA Dao层快速跳转Mapper.xml 文件的插件
  5. 【故障公告】突然猛增的巨量请求冲垮一共92核CPU的k8s集群
  6. excel (2)
  7. Python 循环控制
  8. R数据分析:生存分析与有竞争事件的生存分析的做法和解释
  9. Java设计模式之(三)——建造者模式
  10. Maven 依赖调解源码解析(一):开篇