Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.setState is undefined

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'); } 
like image 637
Natus Drew Avatar asked Aug 29 '16 16:08

Natus Drew


People also ask

Why is setState undefined?

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.

How do I fix setState is not a function?

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.

How do you define setState?

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.

Why putting setState () in render () is not preferred?

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.


1 Answers

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

like image 160
Dmitriy Nevzorov Avatar answered Oct 18 '22 22:10

Dmitriy Nevzorov