javascript - 在反应中,在 Render() 之前执行 API 调用和重定向的最佳方法是什么?
问题描述
我主要做后端,所以我的 javascript 并不是全部,但我在设计的管理面板中遇到了问题。该网站的某些部分只能由某些用户访问。
每次加载受保护的组件时,我都会向我的 REST 服务器发送一个请求,该服务器返回 200 或 403,200 响应包含一个名为 的键redirect
,即False
. 所以我的想法是做以下事情:
...
import { Redirect } from 'react-router-dom';
import axios from 'axios';
class MyProtectedComponent extends Component {
constructor(props) {
super(props);
this.state = {
authCalled: false,
redirect: true,
};
}
componentDidMount() {
console.log("mounting...")
axios.get('<https://url>',
{headers: {"Authorization": localStorage.getItem("token")}})
.then(res => {
this.setState({
redirect: res.data.data.redirect,
authCalled: true,
});
})
}
render() {
if (this.state.authCalled === false) {
return (
<div className="animated fadeIn">
<Row>
<Col>
authenticating...
</Col>
</Row>
</div>
)
}
if (this.state.redirect === true) {
return <Redirect to={{pathname: "/nonauthpage"}} />;
}
return ( ....... <main code> ..... )
现在,如果服务器发回 200 允许用户访问,则组件加载,但如果没有,页面将卡在该<authenticating>
阶段并且永远不会Redirect
s。
我所有的 javascript 都是自学的,如果我正在做的是执行此类事情的坏习惯,请让我知道如何正确地做到这一点,或者告诉我为什么这不起作用,以便我让它工作。
解决方案
您正在使用 axios,这意味着如果响应不是 200(或 2XX),then
则不会执行,而是需要链接执行.catch
如下所示:
componentDidMount() {
console.log("mounting...")
axios.get('<https://url>',
{headers: {"Authorization": localStorage.getItem("token")}})
.then(res => {
this.setState({
redirect: res.data.data.redirect,
authCalled: true,
});
}).catch(error => {
// You can do additional checks here like e.g. check if the response code is 403 or 401
this.setState({
redirect: true,
authCalled: true
});
})
}
推荐阅读
- reactjs - React-传单如何在类中创建变量,该变量将根据对象而变化
- android - 如何从 SAF 文件选择器请求中获取文件路径和文件实例?
- android - 如何在 Android 11+ 上使用范围存储访问 /sdcard/Android/media 文件夹?
- python - ModuleNotFoundError:Jupyter Notebook 上没有名为“_tkinter”的模块
- javascript - 我在等待 Nodejs 中的多个异步函数时遇到问题
- java - 是否有 onPlayerJoin 的客户端版本?
- node.js - Next.js 和 SWR:无法通过 SWR 挂钩中的 API Passport 使用户成功登录
- python - 如何将熊猫数据框转换为指定的字典
- java - Eclipse内置Maven时,如何找到Maven的PATH?
- javascript - 如何在javascript中获取以前的url?