reactjs - 如果我们在 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>
);
}
}
解决方案
推荐阅读
- javascript - 删除对象上的字段,然后删除从中克隆的对象上的字段
- python - 运行 python 脚本时如何绕过 urllib2.HTTP
- mysql - 从 MySQL/MariaDB 表中最近插入的行中选择行
- sql - 以列形式返回结果的动态 SQL 查询
- python - 使用 pandas 总结分类问卷数据
- html - 居中工具提示?
- php - the_post_thumbnail 返回超链接之外
- objective-c - 输出小数点前不为零的浮点数
- java - Textview 未在 FrameLayout 中显示
- python - 使用xlwings在excel中运行python代码