在构造函数或 componentWillMount 中设置初始反应组件状态? [英] set initial react component state in constructor or componentWillMount?
本文介绍了在构造函数或 componentWillMount 中设置初始反应组件状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在react组件中,是在constructor()还是componentWillMount()中设置初始状态?
In react components is it preferred to set the initial state in the constructor() or componentWillMount()?
export default class MyComponent extends React.Component{
constructor(props){
super(props);
this.setState({key: value});
}
}
或
export default class MyComponent extends React.Component{
componentWillMount(props){
this.setState({key: value});
}
}
推荐答案
在使用 ES6 类时最好在构造函数中,但不要使用 setState
API,而是这样做:>
In the constructor is preferable when using ES6 classes, but don't use the setState
API, rather do like so:
export default class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = { key: value };
}
}
此外,如果您有可用的类属性(babel stage 1),那么您可以执行以下操作:
Also, if you have class properties available to you (babel stage 1) then you can do the following:
export default class MyComponent extends React.Component{
state = { key: value };
render() {
....
}
}
这篇关于在构造函数或 componentWillMount 中设置初始反应组件状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文