React 16.13.1触发两次render
2024-10-19 17:21:08
一段很普通的代码,出发了两次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环境下不会这样,所以不用担心
最新文章
- html5标签知多少
- 【原】ZenCoding中常用的CSS3样式
- angular的splitter案例学习
- HDU 5002 Tree LCT 区间更新
- 从运维角度浅谈 MySQL 数据库优化
- 原代码,反码,解释和具体的补充 Java在&;gt;&;gt;和&;gt;&;gt;&;gt;差异
- Java课程设计——GUI密码生成器201521123035
- Indent Guides for Visual Studio 代码格式化收缩插件
- Laravel5笔记--路由
- rem和em学习笔记及CSS预处理(未完待续)
- [c++] opencv加载png
- 苹果App Store审核指南中文翻译(更新至140227)
- 将n的k位清0
- PHP:第二章——PHP中的equire与incude语句
- 深入浅出-网络七层模型&;&;网络数据包
- insert into 的另一种添加插入新行方式
- 关于UI回调Invoker的实现(一)
- dubbo异步调用三种方式
- IIS7日志中时间与系统时间不一致的原因
- (转)Cobbler自动化部署最佳实践