微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如果在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 举报,一经查实,本站将立刻删除。