首页 > 解决方案 > 如果我们在 React 类组件中每次重新渲染后不执行相同的副作用,会有什么区别?

问题描述

我遇到了这个类组件,它有 2 个生命周期方法在每次重新渲染后处理组件的副作用: 我复制了示例(在底部)
componentDidMount并尝试通过删除来使用它,看看如果我不这样做会发生什么处理每次重新渲染的副作用。但似乎没有任何问题;该按钮仍会增加状态。 如果我没记错的话,React 文档说在每次重新渲染中都需要处理副作用,即使它会导致重复。我想知道如果我们不这样做会发生什么坏事。componentDidUpdate
componentDidUpdate

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

标签: reactjsreact-componentside-effectsreact-lifecycle

解决方案


推荐阅读