Dre*_*ams 29 javascript ecmascript-6 reactjs
我发现有两种方法可以在类组件中声明状态,如下所示
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'John'
}
}
render() {
return <div>{this.state.name}</div>
}
}
Run Code Online (Sandbox Code Playgroud)
和
class App extends Component {
state = {
name: 'John'
}
render() {
return <div>{this.state.name}</div>
}
}
Run Code Online (Sandbox Code Playgroud)
这两者有什么区别?
当您想将props数据保存到时使用构造函数state
class App extends Component {
constructor(props){
super(props);
this.state = {
name: 'John'
}
}
}
Run Code Online (Sandbox Code Playgroud)
否则你可以直接设置state硬编码数据
class App extends Component {
state = {
name: 'John'
}
}
Run Code Online (Sandbox Code Playgroud)