Javascript 为什么React官方文档将useEffect与componentDidMount和componentDidUpdate进行比较?
编辑:答案很有帮助,但并不令人满意。我想知道的是,如果Javascript 为什么React官方文档将useEffect与componentDidMount和componentDidUpdate进行比较?,javascript,reactjs,Javascript,Reactjs,编辑:答案很有帮助,但并不令人满意。我想知道的是,如果useffect=componentDidmount+componentdiddupdate+componentWillUnmount,为什么丹·阿布拉莫夫会说“在生命周期中停止思考”?对我来说,在试图理解useffect时,考虑组件生命周期是完美的 在中,useffect与componentDidMount和componentdiddupdate比较如下: useffect: function Example() { const [co
useffect=componentDidmount+componentdiddupdate+componentWillUnmount
,为什么丹·阿布拉莫夫会说“在生命周期中停止思考”?对我来说,在试图理解useffect
时,考虑组件生命周期是完美的
在中,useffect
与componentDidMount
和componentdiddupdate
比较如下:
useffect
:
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
然而在丹·阿布拉莫夫的书中,他说:
停止通过熟悉的类生命周期方法的棱镜来查看useEffect挂钩
在处理钩子时,我试图让自己停止以组件生命周期的方式思考,但官方文档中的示例似乎有意义,我无法区分useffect
示例和componentDidMount
+componentdiddupdate
示例之间的区别
那么这两个例子相同吗?在使用钩子时,我是否应该避免考虑组件生命周期?只有在第一次呈现React元素时才会发生
componentDidMount
事件(可能是为了在组件装载时获取数据)
而另一方面,componentdiddupdate
则在每次更新道具或调用this.setState
时发生
然而,通过使用useffect
钩子,componentDidMount
和componentdiddupdate
背后的功能已经整合到一个回调调用中
现在,您可能会问,为什么React会在这两种生命周期方法之间做出这样的区分
这是因为当第一次加载元素时,某些应用程序可能会以某种方式运行
因此,换句话说,在
useffect
中,您将失去与知道首次装入元素的时间相关的功能。您可以通过提供一个空数组作为useffect
的第二个参数,或者使用ref(通过useRef
hook)保存变量来确定元素是否是第一次装入的,从而重新获得该功能。它们并不完全相同,但用途类似
如果您刚开始学习React(或从事绿地项目),您可能只编写功能组件,因此您可能不需要先学习生命周期方法,但最终您将遇到需要了解React生命周期方法的情况
学习生命周期方法也是很好的,因为有很多React教程和博客文章是在引入hook之前写的
如果您使用React Native,则需要学习这些生命周期方法。没有选择
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>
);
}
}