【问题标题】:Cant setState in componentDidMount [duplicate]无法在 componentDidMount 中设置状态 [重复]
【发布时间】:2018-03-19 23:14:47
【问题描述】:

我正在尝试在 componentDidMount 中设置位置。我猜this 没有被传递给内部函数。

看我的例子:

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const map = {
  width: '100%',
  height: '100vh'
};

const AnyReactComponent = ({ text }) => <div>{ text }</div>;

export default class Map extends Component {
  constructor(props) {
    super(props)
    this.state = {
      center: { lat: 40.7446790, lng: -73.9485420 },
      zoom: 11
    }
  };

  componentDidMount(){
    
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        function(position) {
          console.log(position);

          this.setState({
            center: { lat: position.coords.latitude, lng: position.coords.longitude },
          })              
        }
      )
    }
  }

  render() {
    return (
      <div className='map' style={ map }>
        <GoogleMapReact
          bootstrapURLKeys={{ key: 'AIzaSyD3Gu9y1qJChfayVFglovKEY2xjgKBiCJA' }}
          defaultCenter={ this.state.center }
          defaultZoom={ this.state.zoom }>
          <AnyReactComponent
            lat={ 40.7473310 }
            lng={ -73.8517440 }
            text={ "Where's Waldo?" }
          />
        </GoogleMapReact>
      </div>
    )
  };
};

这种情况一直在发生,我不知道为什么。

你能帮忙吗?

【问题讨论】:

  • 它甚至进入了if语句吗?

标签: reactjs geolocation


【解决方案1】:

首先建议不要在componentDidMount中使用setState。考虑使用 componentWillMount。

其次,您在函数中使用thisthis 不再引用该组件。您可能需要进行臭名昭著的 this->that 转换。

componentWillMount(){

const that = this;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
      console.log(position);

      that.setState({
        center: { lat: position.coords.latitude, lng: position.coords.longitude },
      })              
    }
  )
}

}

【讨论】:

    【解决方案2】:

    您通常不应该更改 componentDidMount() 中的状态。

    阅读docs了解更多信息

    【讨论】:

    • 切换到componentWillMount。仍然收到Uncaught TypeError: Cannot read property 'setState' of null at Map.js:26
    • 不知道为什么这被否决了。建议不要在 componentDidMount 中使用 setState。您应该使用 componentWillMount。但是,如果您确实需要使用它,您可能需要禁用“no-did-mount-set-state”规则(如果已设置)。但这可能会使您的组件陷入错误状态
    【解决方案3】:

    function (position) {} 更改为 ES6 箭头函数 (position) =&gt; {} 以在闭包中保留 this

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

    【讨论】:

      【解决方案4】:

      这个composentDidMount应该更好。箭头函数没有“this”。所以“this”将引用组件。

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

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多