在 Components 类中,我们使用 componentDidMount、componentDidUpdate 生命周期方法来更新状态。前任)
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
Run Code Online (Sandbox Code Playgroud)
它在每次渲染(componentDidUpdate)之后运行,包括第一次渲染(componentDidMount)。在 useEffect 钩子中,我们可以像这样实现这个功能
useEffect(() => {
document.title = `You clicked ${count} times`;
});
Run Code Online (Sandbox Code Playgroud)
这2种方法效果一样吗?
我读了 Reactjs.org 的这一部分,并且在 React.js vs 16 上尝试过。我认为这两种方法具有相同的效果。
useEffect(() => {
document.title = `You clicked ${count} times`;
});
Run Code Online (Sandbox Code Playgroud)