Reactjs Axios-catch()传递道具的可能性?
我试图在axios.catch()函数捕捉到响应错误后设置加载状态,但到目前为止,它只允许错误本身。是否有方法传递状态道具,以便在捕获错误后设置状态Reactjs Axios-catch()传递道具的可能性?,reactjs,axios,Reactjs,Axios,我试图在axios.catch()函数捕捉到响应错误后设置加载状态,但到目前为止,它只允许错误本身。是否有方法传递状态道具,以便在捕获错误后设置状态 this.setState({loading: true}) axios.get(`${wordpressUrl}/wp-json/wp/v2/pages/727?password=${password}`) .then(res => { this.setState({ data: res.data, loading: f
this.setState({loading: true})
axios.get(`${wordpressUrl}/wp-json/wp/v2/pages/727?password=${password}`)
.then(res => {
this.setState({
data: res.data,
loading: false,
visible: true
})
})
.catch((error) => {
if (error.response) {
alert("Invalid password.");
this.setState({ loading: false });
this.forceUpdate();
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
代码示例是我理想中想要实现的
编辑:1
我尝试了以下操作,但.then函数只是跳过response.status else并继续捕获()错误:
.then(response => {
if(response.status === 403) {
alert("Invalid password.");
this.setState({ loading: false });
this.forceUpdate();
} else {
this.setState({
data: response.data,
loading: false,
visible: true
})
}
})
.catch(error => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
我不会将此设置为答案,因此我将编辑我的问题:
我还不太清楚如何将道具传递给捕手,所以我需要制定一个详细的、用户友好的捕手方法。
因此,我做了以下工作:
.catch(error => {
this.setState({loading: false})
console.clear()
console.log(error);
})
如果要向catch块发送变量,可以在其中一个then块内使用
throw
。您可以像使用return
语句一样使用throw
抛出myProps
然后,您将得到
myProps
作为您为catch块声明的参数。谢谢您的回答。我不知道你的意思是什么?我该如何具体实现呢?您可以执行类似于if(response.status==403)throw response的操作,因此现在catch块中的错误变量包含responseah,您已经响应了。是的,我也试过。如果响应是403,它只是跳过.then并转到.catch。所以我可以放一个if(response.status==403),但它永远不会到达那里。