我看到了不同的例子,有些人使用状态,而另一些人使用 this.state。我还是不明白什么时候用什么。在使用 Mapbox 或 Meteor 的示例中,我只看到 this.state。
例1:
export default class SomeComponent extends Component {
state = { someState }
render() {
return (
<Something-to-render-that-uses-state>
);
}
}
例2:
export default class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = { someState }
}
render() {
return (
<Something-to-render-that-uses-state>
);
}
}
最佳答案
当你在类中定义一个变量作为Object类属性初始化时,你不需要使用这个关键字,只需编写state = { someState }
就足够了,但是如果你想在函数或构造函数中定义类变量时,需要使用 this
关键字来指定该变量属于哪个范围
export default class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = { someState }
}
render() {
return (
<Something-to-render-that-uses-state>
);
}
}
关于javascript - 为什么有些人在定义 React 组件时使用 state 而不是 this.state ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50675340/