如果在React类组件中每次重新渲染后不执行相同的副作用,那会有什么不同?

问题描述

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

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>
    );
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...