首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeError:无法读取未定义react的属性“”setState“”

TypeError:无法读取未定义react的属性“”setState“”
EN

Stack Overflow用户
提问于 2020-05-21 18:35:38
回答 1查看 83关注 0票数 0

为什么onMapClicked可以工作,但onGpsClicked不能工作this.setState显示错误TypeError:无法读取未定义的onGpsClicked的属性'setState‘...................................................................................

代码语言:javascript
复制
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,
      });
    });
  }

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-21 18:38:59

代码语言:javascript
复制
   navigator.geolocation.getCurrentPosition(function (position) {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });

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

代码语言:javascript
复制
navigator.geolocation.getCurrentPosition( (position) => {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61932550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档