Home » » this.setState is undefined

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});
}
----Answers------------
1.
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
2.
i hope the below code may give you the idea
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 = {
      zip: '',
      forecast: null
    };
   }

_handleTextChange(event) {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
}

render() {
return (
   <button onChange={e => _handleTextChange(e)}>Click me</button>
  );
 }
}
 

0 nhận xét:

Post a Comment

Popular Posts

Powered by Blogger.