ReactJS protected route with API call(使用API调用的ReactJS受保护路由)
本文介绍了使用API调用的ReactJS受保护路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试保护我在ReactJS中的路线。 在每个受保护的路由上,我要检查保存在本地存储中的用户是否正确。
下面您可以看到我的路线文件(app.js):
class App extends Component {
render() {
return (
<div>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/signup" component={SignUp} />
<Route path="/contact" component={Contact} />
<ProtectedRoute exac path="/user" component={Profile} />
<ProtectedRoute path="/user/person" component={SignUpPerson} />
<Route component={NotFound} />
</Switch>
<Footer />
</div>
);
}
}
我的受保护的路由文件:
const ProtectedRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
AuthService.isRightUser() ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)} />
);
export default ProtectedRoute;
和我的函数isRightUser。此函数在数据对登录的用户无效时发送status(401):
async isRightUser() {
var result = true;
//get token user saved in localStorage
const userAuth = this.get();
if (userAuth) {
await axios.get('/api/users/user', {
headers: { Authorization: userAuth }
}).catch(err => {
if (!err.response.data.auth) {
//Clear localStorage
//this.clear();
}
result = false;
});
}
return result;
}
此代码不起作用,我不知道真正原因。
也许我需要在调用前使用await调用我的函数AuthService.isRightUser(),并将我的函数设置为异步?
如何更新代码以在访问受保护页面之前检查用户?
推荐答案
我遇到了相同的问题,并通过将受保护的路由设置为有状态类来解决该问题。
我使用的内部开关
<PrivateRoute
path="/path"
component={Discover}
exact={true}
/>
我的PrivateRoute类如下
class PrivateRoute extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
isLoading: true,
isLoggedIn: false
};
// Your axios call here
// For success, update state like
this.setState(() => ({ isLoading: false, isLoggedIn: true }));
// For fail, update state like
this.setState(() => ({ isLoading: false, isLoggedIn: false }));
}
render() {
return this.state.isLoading ? null :
this.state.isLoggedIn ?
<Route path={this.props.path} component={this.props.component} exact={this.props.exact}/> :
<Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />
}
}
export default PrivateRoute;
这篇关于使用API调用的ReactJS受保护路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:使用API调用的ReactJS受保护路由
基础教程推荐
猜你喜欢
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- HTML5 画布调整为父级 2022-01-01
