我正在使用React.js,如您所知,componentWillMount()将被弃用.我想替换我componentWillMount的.
我要把它的逻辑转移到constructor.在in componentWillMount和in中执行一些逻辑之间有什么区别constructor吗?
例如,
之前
class Hello extends React.Component {
componentWillMount() {
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
Run Code Online (Sandbox Code Playgroud)
后
class Hello extends React.Component {
constructor(props) {
super(props);
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
Run Code Online (Sandbox Code Playgroud)
另外,当doSomething是setState时,构造函数和公共prop中是否有任何不同的设置状态?
在构造函数中
constructor(props) {
super(props);
this.state = { foo: 1 };
}
Run Code Online (Sandbox Code Playgroud)
在公共道具
state = { foo: 1 };
Run Code Online (Sandbox Code Playgroud)