通过React Native中的fetch设置状态

时间:2017-05-19 22:40:26

标签: javascript reactjs react-native react-native-android

在我的React Native应用程序中,我尝试从API获取特定的响应字符串,并在我的视图中的文本组件中显示它。以下不起作用并返回“TypeError:undefined不是函数(评估_this5.setState ...)

我认为这很简单,但它让我不知所措。

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!');
      }
    })
  }
}

1 个答案:

答案 0 :(得分:3)

使用箭头函数将this词法作用于组件:

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!');
    }
  })
}