【发布时间】:2019-02-05 02:55:47
【问题描述】:
我正在使用 React.js,如您所知,componentWillMount() 将被弃用。
我想替换我的componentWillMounts。
我将把它的逻辑移到constructor。在componentWillMount 和constructor 中执行一些逻辑有什么区别吗?
例如,
之前
class Hello extends React.Component {
componentWillMount() {
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
之后
class Hello extends React.Component {
constructor(props) {
super(props);
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
另外,当doSomething为setState时,constructor和public prop的设置状态有什么区别吗?
在构造函数中
constructor(props) {
super(props);
this.state = { foo: 1 };
}
在公共道具中
state = { foo: 1 };
【问题讨论】:
标签: javascript reactjs