【问题标题】:TypeError: Cannot read property 'setState' of undefined reactTypeError:无法读取未定义反应的属性“setState”
【发布时间】:2020-09-07 23:13:33
【问题描述】:

为什么 onMapClicked 有效但 onGpsClicked 无效 this.setState 显示错误类型错误:无法读取未定义反应的属性“setState”...................................... ..................................................... ..................................................... ......................................

import React from "react";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";
import GpsFixedRoundedIcon from "@material-ui/icons/GpsFixedRounded";
import Button from "@material-ui/core/Button";
export class SimpleMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lat: this.props.lat,
      lng: this.props.lng,
      markers: [
        {
          position: { lat: this.props.lat, lng: this.props.lng },
        },
      ],
    };
    this.onMapClicked = this.onMapClicked.bind(this);
    this.onGpsClicked = this.onGpsClicked.bind(this);
  }

  onMapClicked(t, map, coord) {
    if (this.props.activeStep === 1 || this.props.disable === false) {
      const { latLng } = coord;
      const lat = latLng.lat();
      const lng = latLng.lng();

      this.setState((previousState) => {
        return {
          markers: [
            {
              position: { lat, lng },
            },
          ],
        };
      });

      this.props.onChange(lat, lng);
    }
  }
  onGpsClicked() {
    navigator.geolocation.getCurrentPosition(function (position) {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });
  }

【问题讨论】:

    标签: reactjs


    【解决方案1】:
       navigator.geolocation.getCurrentPosition(function (position) {
          this.setState({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
        });
    

    React 不理解这里的this,因为它指的是函数作用域,而不是 React 作用域。您可以将语法更改为粗箭头函数,它使用词法作用域/this

    navigator.geolocation.getCurrentPosition( (position) => {
          this.setState({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
        });
    

    【讨论】:

    • 更多细节:胖箭头函数自动将你的方法绑定到你的类的上下文。在此之前,你必须写this.myMethod = this.myMethod.bind(this),这已经没有必要了:)
    猜你喜欢
    • 2017-01-01
    • 2018-10-06
    • 2017-05-30
    • 2017-10-30
    • 2021-12-09
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多