Access to it.

Hi, I am new to react so bear with me. I want to save the geolocation as a state. It seems great, since any change in position will cause a render, which is what I want. During development, I have a button that manually fires an event, accessing lastPosition. But when I do. The state is "undefined". Any clue why?

export default class FetchProject extends Component {
  constructor(props) {

  super(props);
  this.state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown',
    };
  }

 //code that sets lastposition
 componentDidMount() {
    ....
 }

 _onPressGET (){
  console.log("PressGET -> " + this.state); //undefined
  var northing=this.state.initialPosition.coords.latitude; //triggers error
 }

render() {
    return (    
      <View style={styles.container}>
        <TouchableHighlight onPress = {this._onPressGET} style = {styles.button}>
          <Text>Fetch mailbox</Text>
        </TouchableHighlight>
      </View>
    );
  }
+4
source share
2 answers

When using ES6 classes of RN watch binding this- thiscan not, as you might think, if you do not have bound her.

onPress = { this._onPressGet.bind(this) }

or in the constructor

constructor(props) {
  super(props);

  this.state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown'
  };

  this._onPressGet = this._onPressGet.bind(this);
}

or maybe the most elegant way

_onPressGet = () => {
  // Function body
}

In order of least preferred.

+17
source

React Docs:

JSX. JavaScript . this.handleClick onClick, undefined, .

, ; , JavaScript. , () , onClick={this.handleClick}, .

0

Source: https://habr.com/ru/post/1659394/


All Articles