Root Cause:

In ES6 class components, this is not bound automatically. So when you call a method like this.setState() inside an event or callback, this may be undefined.

Solution That Can Be Done:

Use arrow functions to preserve this context.

Example Code:

import React, { Component } from 'react';
import { View, TextInput, Alert } from 'react-native';

export default class MyApp extends Component {
  state = {
    zip: ''
  };
  // Arrow function preserves 'this'
  handleTextChange = (event) => {
    const zip = event.nativeEvent.text;
    this.setState({ zip });
    Alert.alert('Zip Updated:', zip);
  };
  render() {
    return (
      <View>
        <TextInput
          placeholder="Enter ZIP"
          onChange={this.handleTextChange}
        />
      </View>
    );
  }
}

 

Need Help With React Native Development?

Work with our skilled React Native developers to accelerate your project and boost its performance.

Hire React Native Developers

Support On Demand!

Related Q&A