I have a component in react native:
export default class Screen extends Component {
constructor(props){
super(props);
this.state = {
prop1: false,
prop2: simpleFunc
};
}
simpleFunc = () => { /*...*/ }
componentWillMount() {
BackgroundGeolocation.on('location', this.onLocation);
The last line is callback method that will be called on new location.
From that method I can't access this.state
or this.simpleFunc()
.
What should I do in order to update state from callback function?
In order to access this
inside onLocation
you need to bind the callback:
componentWillMount() {
BackgroundGeolocation.on('location', this.onLocation.bind(this));
or, you can use an arrow function (which will use the lexical scope of the parent):
componentWillMount() {
BackgroundGeolocation.on('location', (location) => this.onLocation(location));
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