6

Hi I'm new to React so bear with me. I'm want to store geoposition as a state. Seems nifty since any change in position will trigger a render, which is exactly what I want. During development I have a button that manual triggers the event by accessing the 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>
       );
    }
}
kit
  • 1,166
  • 5
  • 16
  • 23
TOMvonMOM
  • 109
  • 1
  • 2
  • 9

2 Answers2

23

When using ES6 classes in RN, watch for binding this - this may not be what you think unless you bind it.

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 from least to most preferential.

NiFi
  • 2,398
  • 1
  • 17
  • 26
Daniel Broad
  • 2,512
  • 18
  • 14
  • Thanks. It works. (But `this.state.initialPosition.coords.latitude`still triggers an error, but that's another story) Why does it get `this`confused? Looking at the code, it seems pretty obvious to me that `this`should refer to the object the method was declared in. – TOMvonMOM Oct 31 '16 at 13:46
  • In this case `this` probably refers to the object that the function is being fired from, like a button or a textbox. – jcollum May 01 '17 at 15:52
  • Great answer. Thankyou – HIRA THAKUR Feb 08 '18 at 09:29
0

Quoted from React Docs:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

Community
  • 1
  • 1
wzso
  • 3,482
  • 5
  • 27
  • 48