How do I call a member function from componentDidMount

javascript reactjs react-native

6736 просмотра

3 ответа

1 Репутация автора

I'm trying to call a function from componentDidMount() after getCurrentPosition() is called. If I pass position to updatePosition the app crashes. If I move the contents of the updatePosition function into getCurrentPosition() then it works. What do I need to do to be able to call a member function from within componentDidMount().

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

      this.state = {
        lat: 0,
        long: 0,
        heading: 0,
        accuracy: 0,
        speed: 0,
        pointCount: 0
      };
  }

  updatePostion(position) {
    var lat = position.coords.latitude;
    this.setState({lat});
  }

  componentDidMount() {
    let self = this;

    setInterval(() => {
      navigator.geolocation.getCurrentPosition((position) => {
        // this breaks
        this.updatePostion(position);

        // if I place the body of updatePosition here it works.
      },
       (error) => {},
       {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
      );
    }, 5000);
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'black'}}>
        <View style={{flex: 1, color: 'green'}}>
          <Text style={styles.green}>
            Position: {this.state.lat}, {this.state.long}
          </Text>
          <Text style={styles.green}>
            Heading: {this.state.heading}
          </Text>
          <Text style={styles.green}>
            Speed: {this.state.speed}
          </Text>
          <Text style={styles.green}>
            Accuracy: {this.state.accuracy}
          </Text>
          <Text style={styles.green}>
            Point Count: {this.state.pointCount}
          </Text>
        </View>
      </View>
    );
  }
}
Автор: Mark Tolson Источник Размещён: 18.07.2016 11:23

Ответы (3)


0 плюса

886 Репутация автора

'self' is not defined inside of updatePostion() that's why you have the error

updatePostion(position) {
    // replace self with this
    self.setState({position.coords.latitude});
}

also you don't need this

let self = this;

inside of componentDidMount() since you use arrow functions

Автор: Alexey Pedyashev Размещён: 18.07.2016 11:24

1 плюс

3071 Репутация автора

Actually, it all works! Here is an RNplay example and its code:

'use strict';

var React = require('react');
var {
  Component,
} = React;
var ReactNative = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = ReactNative;

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

      this.state = {
        lat: 0,
        long: 0,
        heading: 0,
        accuracy: 0,
        speed: 0,
        pointCount: 0
      };
  }

  updatePostion(position) {
    var lat = position.coords.latitude;
    this.setState({lat});
  }

  componentDidMount() {
    setInterval(() => {
      navigator.geolocation.getCurrentPosition((position) => {
        this.updatePostion(position);
      },
       (error) => {},
       {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
      );
    }, 5000);
  }

  render() {
    console.log(this.state);
    return (
      <View style={{flex: 1, padding: 30}}>
        <View style={{flex: 1}}>
          <Text>
            Position: {this.state.lat}, {this.state.long}
          </Text>
          <Text>
            Heading: {this.state.heading}
          </Text>
          <Text>
            Speed: {this.state.speed}
          </Text>
          <Text>
            Accuracy: {this.state.accuracy}
          </Text>
          <Text>
            Point Count: {this.state.pointCount}
          </Text>
        </View>
      </View>
    );
  }
}

AppRegistry.registerComponent('SampleApp', () => GeolocationViewer);

(check the Console Logs)

Автор: damusnet Размещён: 18.07.2016 07:08

0 плюса

10516 Репутация автора

I know this looks ugly, but this is the common issue when you work on react you will face. bind member function inside constructor (ES7 may make it look better, but that will be long time wait)

constructor(props) {
      super(props);

      this.state = {
        lat: 0,
        long: 0,
        heading: 0,
        accuracy: 0,
        speed: 0,
        pointCount: 0
      };

      // in your constructor, add this binding
      this.updatePostion = this.updatePostion.bind(this)
  }
Автор: Xin Размещён: 13.10.2017 10:50
Вопросы из категории :
32x32