IT虾米网

javascript之React Hooks 渲染两次

xiaohuochai 2025年12月25日 程序员 194 0

我定义了一个场景:我们有一个使用父级 Prop 和自身状态的组件。

有两个组件 DC 和 JOKER,我的步骤如下:

  1. 点击 DC 按钮
  2. DC 设置计数
  3. JOKER 将以旧状态渲染
  4. 运行 useEffect 和 setCount
  5. JOKER 再次渲染

我想问为什么 JOKER 渲染两次(第 3 步和第 5 步)而第一次渲染浪费了性能。 我只是不想执行第 3 步如果在类组件中我可以使用 componentShouldUpdate 来避免它。但 Hooks 有同样的东西吗?

我的代码如下,或者打开这个网站https://jsfiddle.net/stephenkingsley/sw5qnjg7/

import React, { PureComponent, useState, useEffect, } from 'react'; 
 
function JOKER(props) { 
  const [count, setCount] = useState(props.count); 
  useEffect(() => { 
    console.log('I am JOKER\'s useEffect--->', props.count); 
    setCount(props.count); 
  }, [props.count]); 
 
  console.log('I am JOKER\'s  render-->', count); 
  return ( 
    <div> 
      <p style={{ color: 'red' }}>JOKER: You clicked {count} times</p> 
    </div> 
  ); 
} 
 
function DC() { 
  const [count, setCount] = useState(0); 
  return ( 
    <div> 
      <p>You clicked {count} times</p> 
      <button onClick={() => { 
        console.log('\n'); 
        setCount(count + 1); 
      }}> 
        Click me 
      </button> 
      <JOKER count={count} /> 
    </div> 
  ); 
} 
 
ReactDOM.render(<DC />, document.querySelector("#app")) 

请您参考如下方法:

It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place. -- gaearon commented on Mar 9, 2019


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!