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不是很熟。
最好的办法使用react-query,如果不想使用的话在类中声明方法时这样声明
如果你不想和this打交道那么就应该使用react hooks