javascript - React-Redux:如果用户未登录,则限制用户访问某些页面的最佳方法
问题描述
我是 React/Redux 的新手,我正在开发一个 React 应用程序。我一直在学习 Redux 的基本概念,例如 Store、Actions、Reducers、Middleware 和 connect() 函数。
但是,对于我的应用程序中的某些页面,我希望只允许登录的用户能够访问它们,否则它们将被重定向回应用程序的主页。
我想知道能够完成这项任务的最佳方法是什么?我听说可以使用 React Router 来做到这一点,但是有没有更好的方法呢?任何见解都值得赞赏。
解决方案
正如您已经建议的路由器,使用它可以安全地使用它,假设用户仅设置为 redux 状态,当在登录中正确验证时:
import { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom':
const mapStateToProps = (state) => {
return {
user: state.user
}
}
class MyPageWrapper extends Component {
componentWillMount() {
if(!this.props.user) this.props.history.push('/login');
}
render() {
return (
<div>
<YourPage/>
</div>
);
}
}
export default connect(mapStateToProps)(withRouter(MyPageWrapper));
推荐阅读
- javascript - 我怎样才能让组件在反应中重新渲染
- sql - Oracle11G 中的查询语法
- algorithm - 假设所有元素都是不同的,那么最小元素可能位于最大堆中的哪个位置?
- javascript - Pass variable into page.evaluate
- d3.js - 如何在 D3 中将 unix 时间戳转换为日期对象?
- javascript - 为什么这个while循环永远循环?
- javascript - 使用正则表达式 javascript 基于字符串集的逗号分隔值分组
- javascript - Discord.js message.react 不是函数
- java - 在 Java 中创建具有多种数据类型的列表的最简单方法是什么?
- node.js - 使用 N-API 进行资源共享?