严格模式无法自动为您检测副作用,但它可以可以通过使它们更具确定性来帮助您发现它们.这是通过有意重复调用以下函数来实现的:类组件constructor、render和shouldComponentUpdate方法类组件静态getDerivedStateFromProps方法函数组件主体状态更新器函数(setState 的第一个参数)传递给 useState、useMemo 或 useReducer 的函数这只适用于开发模式.Consider the canonical useState example:import React, { useState } from 'react';const MyComponent = () => { const [count, setCount] = useState(0); console.log(count); return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}> count: {count} <button onClick={() => setCount(count + 1)}>Increment</button> </div> );};export default MyComponent;Clicking the button makes each state print twice. Why is that? 解决方案 Put the console.log in an useEffect hook without dependencies and you'll see it isn't actually rendering twice.import React, { useEffect, useState } from 'react';const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { console.log(count); }); return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}> count: {count} <button onClick={() => setCount(count + 1)}>Increment</button> </div> );};export default MyComponent;Here's a good diagram of the component lifecycle, it lists the class-based lifecycle functions, but the render/commit phases are the same.The import thing to note is that the component can be "rendered" without actually being committed (i.e. the conventional render you see to the screen). The console.log alone is part of that. The effects run after in the "commit" phase.useEffectReact Strict ModeDetecting Unexpected Side-effectsThis only applies to development mode. 这篇关于React useState 导致双重渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-18 08:54