Javascript 无法通过react jsx传递状态值。获取错误-意外标记:“此”
下面的代码将状态键初始化为NULL,并在安装组件时为它们指定某些值。这一切都很好 问题在于在渲染函数中访问这些状态值。 在地图组件中,initialCenter属性将对象作为值。这是我传递状态值并得到以下错误的地方 未能编译 ./src/components/Mapcontainer.js 第32:21行:分析错误:意外的关键字“this”Javascript 无法通过react jsx传递状态值。获取错误-意外标记:“此”,javascript,reactjs,jsx,react-state-management,react-state,Javascript,Reactjs,Jsx,React State Management,React State,下面的代码将状态键初始化为NULL,并在安装组件时为它们指定某些值。这一切都很好 问题在于在渲染函数中访问这些状态值。 在地图组件中,initialCenter属性将对象作为值。这是我传递状态值并得到以下错误的地方 未能编译 ./src/components/Mapcontainer.js 第32:21行:分析错误:意外的关键字“this” export class MapContainer extends Component { constructor() { super();
export class MapContainer extends Component {
constructor() {
super();
this.state = {
lat: null,
lng: null,
};
}
componentDidMount() {
navigator.geolocation.watchPosition((position) => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
}
render() {
return (
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{
lat: {this.state.lat},
lng: {this.state.lng},
}}
>
<Marker />
</Map>
);
}
}
应该是
initialCenter={this.state}
或
因为在前一种情况下,将有嵌套对象。和lat:{this.state.lat}将导致语法错误,因为{this.state.lat}将导致没有键的对象
应该是
initialCenter={this.state}
或
因为在前一种情况下,将有嵌套对象。和lat:{this.state.lat}将导致语法错误,因为{this.state.lat}将导致对象没有键。无需将javascript代码再次包装在lat:{this.state.lat}或lng:{this.state.lng}的大括号中。就这么做吧
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{ // one for expression evaluation and one for object literal
lat: this.state.lat,
lng: this.state.lng,
}}
>
有关更多说明,请参阅下面的stackoverflow线程
.无需在lat:{this.state.lat}或lng:{this.state.lng}的大括号中再次包装javascript代码。就这么做吧
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{ // one for expression evaluation and one for object literal
lat: this.state.lat,
lng: this.state.lng,
}}
>
有关更多说明,请参阅下面的stackoverflow线程