TypeError:_this2.setState不是函数,无法绑定状态

时间:2018-09-09 08:03:15

标签: android reactjs react-native bind es6-class

我收到此错误。因为我已经在使用ES6格式,所以该箭头也会出现相同的错误。并在某种程度上混淆了如何使用绑定。我如何摆脱这个错误。

代码:

async fetchData() {
    const { navigate } = this.props.navigation;
    var DEMO_TOKEN = await AsyncStorage.getItem(STORAGE_KEY);
    NetInfo.isConnected.fetch().then((isConnected) => {
    if ( isConnected )
    {
       return fetch(`${url}`,
    {
      method: "GET",
      headers: {
        'Authorization': `JWT ${DEMO_TOKEN}`,
      }
    })
       .then(
          function(response) {
              console.log(response.headers);
              console.log(response.status);
              console.log(response.url);
              if (response.status !== 200) {
                  console.log('Status Code: ' + response.status);
                  return;
              }

              response.json().then((responseData) => {
                  console.log(responseData);
                  this.setState({
                     ver: responseData.results.appversion, // getting error here
                  });
              });
          }
      )
      .catch(function(err) {
          console.log('Fetch Error', err);
      });

1 个答案:

答案 0 :(得分:1)

只是要弄清楚您要引用哪个this,您可以这样做吗?

async fetchData() { const ctx = this

然后引用ctx而不是this

ctx.setState({ ver: responseData.results.appversion, });