Javascript 为什么有些人在定义React组件时使用state而不是this.state?
我看到了不同的例子,其中一些人使用state,而另一些人使用this.state。我还是不明白什么时候用什么。在使用Mapbox或Meteor的示例中,我只看到这个.state 例1:Javascript 为什么有些人在定义React组件时使用state而不是this.state?,javascript,reactjs,meteor,mapbox-gl-js,Javascript,Reactjs,Meteor,Mapbox Gl Js,我看到了不同的例子,其中一些人使用state,而另一些人使用this.state。我还是不明白什么时候用什么。在使用Mapbox或Meteor的示例中,我只看到这个.state 例1: 导出默认类SomeComponent扩展组件{ state={someState} render(){ 返回( ); } } 例2: 导出默认类SomeComponent扩展组件{ 建造师(道具){ 超级(道具); this.state={someState} } render(){ 返回( ); } } 当您
导出默认类SomeComponent扩展组件{
state={someState}
render(){
返回(
);
}
}
例2:
导出默认类SomeComponent扩展组件{
建造师(道具){
超级(道具);
this.state={someState}
}
render(){
返回(
);
}
}
当您将类中的变量定义为初始化的对象类属性时,不需要使用此关键字,只需编写state={someState}
就足够了,但是如果您想在函数或构造函数中定义类变量,您需要使用this
关键字来指定变量所属的范围
export default class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = { someState }
}
render() {
return (
<Something-to-render-that-uses-state>
);
}
}
导出默认类SomeComponent扩展组件{
建造师(道具){
超级(道具);
this.state={someState}
}
render(){
返回(
);
}
}
状态={}声明是一个类属性,它当前不是JavaScript语言的一部分。某些实用程序(如Babel)会将其编译成合法的JavaScript代码
所以这完全是一样的。看看babel将代码传输到的JavaScript。没有区别
export default class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = { someState }
}
render() {
return (
<Something-to-render-that-uses-state>
);
}
}
export default class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = { someState }
}
render() {
return (
<Something-to-render-that-uses-state>
);
}
}