Chr*_*che 2 authentication reactjs react-router redux
我正在尝试使用react,react-router和redux设置一个新的前端项目,我在设置一个运行良好且有很多页面的登录工作流程时遇到了绊脚石.
这是我想要的逻辑:
logged: true/false
.logged
从登录页面设置为true,则重定向到我们重定向的页面,或者重定向到/
未定义的页面.以前的位置存储在nextPathname
. logged
设置为false
需要身份验证的组件,重定向到/
.我对这个工作流程的主要问题是我想调度一个动作(设置记录的值),然后进行重定向.
以下是我探索过的一些替代方案:
logged==true
在我的登录组件中componentWillReceiveProps
并重定向是否是这种情况.这适用于登录工作流,但如果我必须为注销组件实现这样的逻辑,我必须为需要auth的每个组件执行此操作.(由于ES6反应成分,Mixins不起作用......).所以我的问题是:如何在所有受限制的页面上进行auth工作而不会产生太多开销?
一点代码:
app.js:
function requireAuth(nextState, replace) {
if(store.getState().Login.logged === false) {
replace({
pathname: "/login",
state: { nextPathname: nextState.location.pathname }
});
}
}
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Archives} onEnter={requireAuth}></Route>
<Route path="/login" component={LoginComponent}></Route>
</Router>
</Provider>,
document.getElementById("app")
);
Run Code Online (Sandbox Code Playgroud)
LoginComponent:
class LoginComponent extends React.Component<LoginProps, any> {
componentWillReceiveProps(newProps) {
if(newProps.logged) {
let nextPath = "/";
const {location, history} = newProps;
if (location.state && location.state.nextPathname) {
nextPath = location.state.nextPathname;
}
history.pushState({}, nextPath);
}
}
render() {
return <div>This is a login form</div>
}
}
Run Code Online (Sandbox Code Playgroud)
我相信,您希望这样做的方法是使用"RequireAuth"高阶组件来包装用户需要进行身份验证才能访问的组件.这是一个这样的例子,只需注意客户端文件夹中的auth组件:https://github.com/joshuaslate/mern-starter