Cas*_*e09 5 authentication reactjs react-router redux react-router-v4
我正在将React Router v4与redux一起使用,并且如果用户未登录,我想利用私有和受保护的路由进行重定向。
我有这个路线组件:
class Routes extends Component {
render() {
const { auth } = this.props;
// so checks against isAuthenticated can pass
if (auth.isAuthenticated !== undefined) {
return (
<div>
<Route exact component={() => <Home />} />
<PublicRoute
authed={() => auth.isAuthenticated}
path="/login"
component={(routerProps) => <Login {...routerProps} />}
/>
<PublicRoute
authed={() => auth.isAuthenticated}
path="/register"
component={(routerProps) => <Register {...routerProps} />}
/>
<PrivateRoute
authed={() => auth.isAuthenticated}
path="/dashboard"
component={Dashboard}
/>
</div>
);
} else {
return <div></div>
}
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default withRouter(connect(mapStateToProps)(Routes));
Run Code Online (Sandbox Code Playgroud)
它是这样实现的:
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是PrivateRoute:
export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
<Route
{...rest}
render={props =>
isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
传递该auth道具的最佳方法是什么,如果我连接Routes组件并auth从那里传递可以,还是应该从其他地方传递出去,也许连接需要它的每个组件并从那里读取?另外,这种方法如何与嵌套路线一起使用,例如/dashboard/settings?谢谢
其实在react中使用这种私有路由是可以的,但是你应该检查两个时刻:
我应该检查一下,您没有exact属性,因此您的所有路线(例如/dashboard/panel1, ) /dashboard/panel2将是私有的
auth.isAuthenticated} path="/dashboard" 组件={Dashboard} />
连接时您会遇到一些问题。有一个简单的解决方法:
导出默认连接(mapStateToProps, null, null, { pure: false, })(PrivateRoute);
更多信息在这里: React 路由器私有路由/重定向不起作用
| 归档时间: |
|
| 查看次数: |
5161 次 |
| 最近记录: |