react/redux中的身份验证工作流程

Chr*_*che 2 authentication reactjs react-router redux

我正在尝试使用react,react-router和redux设置一个新的前端项目,我在设置一个运行良好且有很多页面的登录工作流程时遇到了绊脚石.

这是我想要的逻辑:

  1. 在redux商店中有一个变量,表示我是否登录.为了简化,我们说有logged: true/false.
  2. 如果logged从登录页面设置为true,则重定向到我们重定向的页面,或者重定向到/未定义的页面.以前的位置存储在nextPathname.
  3. 何时logged设置为false需要身份验证的组件,重定向到/.

我对这个工作流程的主要问题是我想调度一个动作(设置记录的值),然后进行重定向.

以下是我探索过的一些替代方案:

  1. 检查是否logged==true在我的登录组件中componentWillReceiveProps并重定向是否是这种情况.这适用于登录工作流,但如果我必须为注销组件实现这样的逻辑,我必须为需要auth的每个组件执行此操作.(由于ES6反应成分,Mixins不起作用......).
  2. 处理中间件中的重定向:当操作是关于登录时,运行操作然后重定向.但是我不知道这是不是最好的做法.

所以我的问题是:如何在所有受限制的页面上进行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)

Jos*_*ate 5

我相信,您希望这样做的方法是使用"RequireAuth"高阶组件来包装用户需要进行身份验证才能访问的组件.这是一个这样的例子,只需注意客户端文件夹中的auth组件:https://github.com/joshuaslate/mern-starter