TypeError:无法读取未定义反应的属性“ setState”

时间:2020-05-21 10:35:37

标签: reactjs

为什么onMapClicked起作用但onGpsClicked不能起作用this.setState show Error TypeError:无法读取未定义反应的属性'setState'............................... ................................................... ................................................... ....................................................

enter image description here

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,
      });
    });
  }

1 个答案:

答案 0 :(得分:4)

node.undersideACFgraphql.mainText

React在这里不理解const IndexPage = (props) => { const { indexImage, wpgraphql } = props.data return ( <Layout> <SEO title="Home" /> <BackgroundImage className="masthead" fadeIn fluid={indexImage.childImageSharp.fluid} > <div className="black-overlay"> <div className="content-box"> <h1>Her skriver jeg en overskrift</h1> <h2>This is my sub head</h2> </div> </div> </BackgroundImage> <div style={{ margin: `0 auto`, maxWidth: 1200, padding: `0 1.0875rem 1.45rem`, }} > <div class="wrapper"> <div class="box a"> {wpgraphql.pages.edges[0].node.undersideACFgraphql.mainText} </div> <div class="box b">Her skriver jeg tekst 2 :D</div> </div> </div> <Link to="/page-2/">Gå til en anden side</Link> </Layout> ) } ,因为它指的是函数范围,而不是React范围。您可以使用词法作用域/ this

将语法更改为胖箭头功能
   navigator.geolocation.getCurrentPosition(function (position) {
      this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      });
    });