TOMvonMOM
TOMvonMOM

Reputation: 209

Accessing this.state in React-Native

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>
       );
    }
}

Upvotes: 6

Views: 13028

Answers (2)

wzso
wzso

Reputation: 3905

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.

Upvotes: 0

Daniel Broad
Daniel Broad

Reputation: 2522

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.

Upvotes: 23

Related Questions