react / redux

时间:2016-05-19 12:50:41

标签: authentication reactjs react-router redux

我正在尝试使用react,react-router和redux设置一个新的前端项目,而且我在设置适用于多页的登录工作流时遇到了绊脚石。

这是我想要的逻辑:

  1. 在redux商店中有一个变量,表示我是否已登录。为了简化,我们说logged: true/false
  2. 从登录页面将logged设置为true时,重定向到我们重定向的页面,如果未定义,则重定向到/。之前的位置存储在nextPathname中。
  3. 在需要身份验证的组件中将logged设置为false时,会重定向到/
  4. 我对这个工作流程的主要问题是我想调度一个动作(设置记录的值),然后进行重定向。

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

    1. 检查我的登录组件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不会工作......)。
    2. 处理中间件中的重定向:当操作是关于登录时,运行操作然后重定向。但是,我不知道这是否是最佳做法。
    3. 所以我的问题是:如何在所有受限制的页面上进行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

1 个答案:

答案 0 :(得分:5)

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