React Hooks渲染两次 [英] React Hooks render twice

查看:1011
本文介绍了React Hooks渲染两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个场景:我们有一个使用父母的道具及其自身状态的组件.

I define a scene: we have a component that uses parent's props and itself state.

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

There are two Components DC and JOKER and my step under the below:

  1. 单击DC的按钮
  2. DC setCount
  3. JOKER将使用旧状态进行渲染
  4. 运行useEffect和setCount
  5. JOKER再次渲染

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

I want to ask why JOKER render twice(step 3 and 5) and the first render squanders the performance. I just do not want step 3. If in class component I can use componentShouldUpdate to avoid it. But Hooks has the same something?

下面的我的代码,或打开此网站 https://jsfiddle.net/stephenkingsley/sw5qnjg7/

My code under the below, or open this website 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"))

推荐答案

这是StrictMode的故意功能.这仅在开发过程中发生,并有助于发现在渲染阶段出现的意外副作用.我们只对带有挂钩的组件执行此操作,因为这些组件很可能在错误的地方意外地产生了副作用. -加龙(Gaearon)

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

引用: https://github.com/facebook/react/issues/15074

这篇关于React Hooks渲染两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆