【问题标题】:setState in componentDidMount() not working in geolocation callbackcomponentDidMount() 中的 setState 在地理定位回调中不起作用
【发布时间】:2016-07-11 08:33:10
【问题描述】:

我是 react-native 的新手,我正在尝试使用地理位置来更新状态。

在 componentDidMount() 中,我可以调用 this.setState({lat: 1}); 并且它可以工作。但是,如果我从 geolocation.getCurrentPosition() 回调中调用this.setState({lat: 1});,应用程序就会崩溃。我正在物理设备上进行测试。

我已剥离一切以隔离问题。非常感谢任何帮助。

这是我的代码:

 import React, { Component } from 'react';
 import { AppRegistry,ScrollView, ListView, Text, View } from 'react-native';

 class TestProject extends Component {
   constructor(props) {
      super(props);

      this.state = {
        lat: 0
      };
  }

   componentDidMount() {
      navigator.geolocation.getCurrentPosition(function(position) { 
        this.setState({lat: 1}); // this causes a crash - without this line the app does not crash.
      },
       (error) => alert(error.message)
     );

     this.setState({lat: 1}); // this works
  }

   render() {
     return (
       <View>
        <Text>
          {this.state.lat}
        </Text>
       </View>
     );
   }
 }

AppRegistry.registerComponent('TestProject', () => TestProject);

【问题讨论】:

  • let self = this; navigator.geolocation.getCurrentPosition(function(position) { self.setState({ lat: 1 }); }, (error) =&gt; alert(error.message) );- 这对我有用。
  • @Phil 它的工作原理谢谢!我虽然你不必用 ES6 来做这件事,但我找不到任何使用这种技术的例子?不管怎样,谢谢!
  • 很高兴听到!是的...有时您必须使用this 设置一个var/let。例如,当您使用 forEach 并希望访问此 forEach 之外的范围时。

标签: javascript android geolocation react-native state


【解决方案1】:

感谢@Phil,我只需要设置self = this

let self = this; 
navigator.geolocation.getCurrentPosition(function(position) { self.setState({ lat: 1 }); }, (error) => alert(error.message) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多