Undefined is not an object evaluating this.state.*

后端 未结 4 1028
不思量自难忘°
不思量自难忘° 2021-01-04 03:33

I\'m having an issue with posting data to an express REST API I have using fetch in my react-native app. Here\'s my code:

/**
 * Sample React Na         


        
相关标签:
4条回答
  • 2021-01-04 03:36

    You should bind in your constructor not in the render function. In your constructor, just add:

    this.addData = this.addDate.bind(this);

    You can also use ES6 as another alternative:

    addData = () => { ... }

    That will work to as documented here: https://babeljs.io/blog/2015/06/07/react-on-es6-plus under the arrow function section.

    0 讨论(0)
  • 2021-01-04 03:39

    React handlers are not automatically bound to the element/class they are in.

    <Button onPress={this.addData.bind(this)}>Add data</Button>
    

    https://facebook.github.io/react/docs/handling-events.html

    Excerpt from above link

    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
    
    0 讨论(0)
  • 2021-01-04 03:54

    In case of react, make addData() as arrow function like this:

    addData = () => {
    
        ... 
    
    }
    
    0 讨论(0)
  • 2021-01-04 03:58

    Probably you need to bind the context. In your onClick method add something like this: onClick={this.addData.bind(this)}. This way the method can have access to the state object.

    0 讨论(0)
提交回复
热议问题