【问题标题】:Unable to pass state value through react jsx. Getting error - Unexpected token : 'this'无法通过 react jsx 传递状态值。出现错误 - 意外令牌:'this'
【发布时间】:2020-10-27 09:18:52
【问题描述】:

以下代码将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>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs jsx react-state-management react-state


    【解决方案1】:
    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} 会导致对象没有键。

    【讨论】:

      【解决方案2】:

      对于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线程。

      what-is-the-purpose-of-double-curly-braces-in-reacts-jsx-syntax.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-28
        • 1970-01-01
        • 2017-01-24
        • 1970-01-01
        • 1970-01-01
        • 2016-07-10
        • 2016-08-24
        • 2021-10-13
        相关资源
        最近更新 更多