I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.
import React, { Component } from 'react'; import { View, Text, TextInput, StyleSheet } from 'react-native'; export default class MyWeatherApp extends Component { constructor(props) { super(props); this.state = {}; } getInitialState() { return { zip: '', forecast: null, }; } _handleTextChange(event) { var zip = event.nativeEvent.text; this.setState({zip: zip}); }
Solution:
_handleTextChange = (event) => { var zip = event.nativeEvent.text; this.setState({zip: zip}); alert('click'); }
The "cannot read property 'setState' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
There are two ways to fix this error: Declare the class method using the arrow function syntax. Bind the class method reference during constructor call or inside the calling property.
It ensures that the component has been updated and calls for re-rendering of the component. setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console.
The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser. In this case, avoid using setState() here.
When you extend
React.Component
with ES2015 class syntax you need to bind your action handlers to a context of your class.
Try this: onChange={e => _handleTextChange(e)}
Generally, it's better not to use arrow functions or bind
methods inside render
as it generates a new copy of the function on any render
call. Move function declaration to the class constructor
.
I personally prefer to use arrow functions as class properties in this case
class MyClass extends React.Component { handleClick = () => { // your logic }; render() { return ( <button onClick={this.handleClick}>Click me</button> ); } }
It's not a part of ES2015 specification but babel stage-0 preset supports this syntax
You can read more about context binding in React in this article
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