react 组件里面fetch数据失败了,怎么改变当前组件状态?

fetch("http://xxxxx.com/a/b")
            .then(function (resp) {
                if (!resp.ok) {
                    throw new Error('Network response was not ok.');
                }
                DebugPrint(resp);
                return resp.json();
            }).then((respJson) => {
                DebugPrint(respJson);
                this.setState({
                    list: respJson
                })
                console.log(this.state.list)
            }).catch(function (error) {
                console.log('There has been a problem with your fetch operation: ', error.message);
            });

resp.ok == false的时候,抛出了个错误,到了catch里面,我想在catch里面改变当前组件状态,展示一个error的提示,我发现在第一个then和catch都不能使用this.setState,没有了this对象,要如何解决这个问题?js不是很熟。

阅读 2.1k
1 个回答

最好的办法使用react-query,如果不想使用的话在类中声明方法时这样声明

class Comp extends React.Component {
   someHanlder = () => {
      //在其中可以正确的获得this
   }
}

如果你不想和this打交道那么就应该使用react hooks

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题