javascript - 无法通过 react jsx 传递状态值。出现错误 - 意外令牌:'this'
问题描述
以下代码将state
键初始化为NULL
并在安装组件时为其分配某些值。(这一切都很好)
问题在于在render
函数中访问这些状态值。在Map
组件中,initialCenter
属性以对象为值。这是我传递状态值并得到以下错误的地方。
无法编译 ./src/components/Mapcontainer.js 第 32:21 行:解析错误:意外的关键字“this”
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={{
lat: {this.state.lat},
lng: {this.state.lng},
}}
应该
initialCenter={this.state}
或者
initialCenter={{
lat: this.state.lat,
lng: this.state.lng
}}
因为在前面的例子中你会有嵌套的对象。并且lat: {this.state.lat}
会导致语法错误,因为{this.state.lat}
会导致对象没有键。
推荐阅读
- javascript - 等待变量改变
- python-3.x - 高级搜索 API,使用 retweets_of 和 from 函数
- javascript - jsPDF 生成一个带有拉伸元素的 pdf
- visual-studio - 如何修复 CS0234 - 缺少装配参考
- amp-html - 是否可以选择使用 AMP 从电子邮件中上传照片/视频?
- jolt - 比较和组合相同数组的对象
- r - R数据框插入基于其他数据框的值
- excel - Excel VBA Range 'Delete' 方法随机失败
- c# - 当列表中不存在值时如何比较对象和List<>和object.value null
- adobe - 如何在 ADOBE XD 上显示工具栏