【问题标题】:TypeError: _this2.setState is not a function, Cant bind stateTypeError:_this2.setState 不是函数,无法绑定状态
【发布时间】:2018-09-09 08:03:15
【问题描述】:

我收到这个错误。因为我已经在使用 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);
      });

【问题讨论】:

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


    【解决方案1】:

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

    async fetchData() { const ctx = this

    然后引用ctx 而不是this

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

    【讨论】:

    • 耶...非常感谢。我明白了。
    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 2019-02-21
    • 2020-06-01
    • 1970-01-01
    • 2018-07-19
    • 2017-07-18
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多