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>
);
}
}
React Native - State. The data inside React Components is managed by state and props. In this chapter, we will talk about state. Difference between State and Props. The state is mutable while props are immutable. This means that state can be updated in the future while props cannot be updated.
React State 1 Creating the state Object. 2 Using the state Object. 3 Changing the state Object. To change a value in the state object, use the this.setState () method. When a value in the... More ...
If you’re using React hooks in a component with an event listener, your event listener callback cannot access the latest state. We can incorporate useRef to solve this problem.
As setState is an operation, you can just wait till the value is set by React. You might wait for a certain period to access the updated state using
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With