我刚开始反应JS编码..。我想知道任何方法在基于类的组件中被调用,只要它得到道具,并且在它们的呈现返回方法中被另一个组件调用。事实上!每当该组件被另一个组件呈现或调用时,我都希望运行该函数。我很感激你..。
发布于 2022-05-02 19:48:12
在React类组件中,render方法本身不应该造成副作用。现在还为时尚早--我们通常希望在React更新DOM之后执行我们的效果。
这就是为什么在React类中,我们将副作用引入到componentDidMount和componentDidUpdate中。回到我们的示例,这里有一个React计数器类组件,它在React对DOM进行更改之后立即更新文档标题:
class Example 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类组件没有这样的方法。我们可以提取一个单独的方法,但我们仍然需要在两个地方调用它。
https://stackoverflow.com/questions/72091444
复制相似问题