Reactjs 如果我们不';在React类组件中每次重新渲染后,是否执行相同的副作用?
我发现这个类组件有两个生命周期方法,在每次重新渲染后处理组件的副作用:Reactjs 如果我们不';在React类组件中每次重新渲染后,是否执行相同的副作用?,reactjs,react-component,side-effects,react-lifecycle,Reactjs,React Component,Side Effects,React Lifecycle,我发现这个类组件有两个生命周期方法,在每次重新渲染后处理组件的副作用: componentDidMount和componentdiddupdate 我复制了示例(在底部),并尝试通过删除componentdiddupdate来处理它,以查看如果每次重新渲染时不处理副作用会发生什么。但似乎什么都没有打破;按钮仍会增加状态。 如果我没有弄错的话,React文档说,每次重新渲染都需要处理副作用,即使它会导致重复。我想知道如果我们不这样做会发生什么坏事 import React from "
componentDidMount
和componentdiddupdate
我复制了示例(在底部),并尝试通过删除
componentdiddupdate
来处理它,以查看如果每次重新渲染时不处理副作用会发生什么。但似乎什么都没有打破;按钮仍会增加状态。如果我没有弄错的话,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>
);
}
}
从“React”导入React;
导入“/styles.css”;
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
计数:0
};
}
componentDidMount(){
document.title=`您单击了${this.state.count}次';
}
componentDidUpdate(){
document.title=`您单击了${this.state.count}次';
}
render(){
返回(
您单击了{this.state.count}次
this.setState({count:this.state.count+1})}>
点击我
);
}
}
您能链接到您看到的文档吗?没有这样的规定。事实上,最好让副作用代码只运行一次。在你的例子中,这并不重要,因为副作用是幂等的。寻找“注意我们必须如何在类中的这两个生命周期方法之间复制代码”。当您希望在“首次装载”和后续“更新”期间运行副作用时,这是相关的。它们不会在每次渲染时运行两次。