我正在尝试使用react,react-router和redux设置一个新的前端项目,而且我在设置适用于多页的登录工作流时遇到了绊脚石。
这是我想要的逻辑:
logged: true/false
。 logged
设置为true时,重定向到我们重定向的页面,如果未定义,则重定向到/
。之前的位置存储在nextPathname
中。 logged
设置为false
时,会重定向到/
。 我对这个工作流程的主要问题是我想调度一个动作(设置记录的值),然后进行重定向。
以下是我探讨的一些替代方案:
logged==true
中的componentWillReceiveProps
是否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")
);
,如果是这样,则重定向。这适用于登录工作流,但如果我必须为注销组件实现这样的逻辑,我必须为需要auth的每个组件执行此操作。 (由于ES6反应成分,Mixins不会工作......)。 所以我的问题是:如何在所有受限制的页面上进行auth工作而不会产生太多开销?
一些代码:
app.js:
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>
}
}
LoginComponent:
OnClick
答案 0 :(得分:5)
我认为,您希望解决此问题的方法是使用“RequireAuth”高阶组件来包装用户需要进行身份验证才能访问的组件。这是一个例子,只需注意客户端文件夹中的auth组件:https://github.com/joshuaslate/mern-starter