简体   繁体   中英

Setting state through fetch in React Native

In my React Native app I am trying to fetch a particular response string from my API and display it within a text component in my view. The below does not work and returns "TypeError: undefined is not a function(evaluating _this5.setState...)

I think it's something simple but it's eluding me.

export default class Test extends Component {

  constructor (props) {
    super(props);
    this.state = {
      current: 'Blank',
    }
  }

  render () {
    return (
      <View>
        {this.state.current}  
      </View>   
    );
  }

  postRequest (data) {
    fetch('https://????/controllers/ajaxController.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      body: "main=" + parseInt(data),
    })
    .then(function (response) {
      responseData = response.json();
      if (response.status == 200) {
        return responseData.then((data) => this.setState({ current: data[0] }));
      }  else {
        throw new Error('Server Error!');
      }
    })
  }
}

Use arrow functions to have this lexically scoped to the component:

postRequest = (data) => {
  fetch('https://????/controllers/ajaxController.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    body: "main=" + parseInt(data),
  })
  .then((response) => {
    responseData = response.json();
    if (response.status == 200) {
      return responseData.then((data) => this.setState({ current: data[0] }));
    } else {
      throw new Error('Server Error!');
    }
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM