首页 > 解决方案 > 无法通过 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>
    );
  }
}

标签: javascriptreactjsjsxreact-state-managementreact-state

解决方案


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}会导致对象没有键。


推荐阅读