在构造函数和 componentWillMount 中哪种初始化更合适? [英] Which kinds of initialization is more appropriate in constructor vs componentWillMount?

查看:33
本文介绍了在构造函数和 componentWillMount 中哪种初始化更合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个需要一些设置的 React 组件(例如计时器或 WebAudio API 等),我在决定初始化是否应该在 constructorcomponentWillMount 中遇到困难.两者有什么优点或缺点吗?我不清楚哪个地方更适合这种情况.

If I have a React component that requires some setup (e.g. for timers, or WebAudio API, etc), I'm having trouble deciding whether the initialization should go in constructor or componentWillMount. Is there any advantages or disadvantages to either one? It's not clear to me which one is the better place for this.

我在谷歌上搜索了一下,看看是否有人讨论过 constructorcomponentWillMount 之间的区别,但我找不到任何东西.

I Googled around a bit to see if anyone had discussed the differences between constructor and componentWillMount but I couldn't find anything.

Redux 和任何异步函数不应该是等式的一部分.

Redux and any asynchronous functions should not be part of the equation.

推荐答案

通常情况下,如果您的组件是有状态的,您在构造函数中所做的唯一一件事就是分配您的初始 this.state.你不应该在构造函数中做任何其他事情.

Normally the only thing you do in the constructor is assign your initial this.state if your component is stateful. You should not do anything else in the constructor.

componentWillMount 通常是不必要的.我会说在大多数情况下它的使用是一种反模式.人们使用它的一个原因是在渲染之前最后一次从外部源更新状态,但从技术上讲,在构造函数中分配它是等效的.它提供的唯一次要便利是您可以在它内部 setState 但不能在构造函数内部.

componentWillMount is generally unnecessary. I would say in most cases its use is an anti-pattern. One reason people use it is for updating the state from an external source one last time before rendering but technically assigning it in the constructor is equivalent. The only minor convenience it affords is that you can setState inside it but you can’t inside the constructor.

对于任何副作用(数据获取或 DOM 操作),您应该使用 componentDidMount.

For any side effects (data fetching or DOM manipulation) you should use componentDidMount.

这篇关于在构造函数和 componentWillMount 中哪种初始化更合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆