首页 > 解决方案 > React Redux Auth 中间件

问题描述

我正在使用 react/redux 做一个登录应用程序,这是我的流程。

我有一个 PrivateRoute 用于进行身份验证检查,但是我想触发对所有路由的身份验证检查,而不仅仅是私有路由。这样,如果用户正在查看主页,我仍然可以在导航中显示他的名字(例如) 主要问题似乎是调用 auth 操作的正确位置。

应用程序.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from 'react-redux';
import store from './store';

// Styling
import './App.css';

// Privat route
import PrivateRoute from './routes/PrivateRoute';

// Common
import Navigation from './components/common/Navigation';

// Components
import Login from './components/Login';
import Home from './components/Home';
import Profile from './components/Profile';
import ArticlesList from './components/Profile/ArticlesList';
import ArticleForm from './components/Profile/ArticleForm';

const App = () => (
    <Provider store={store}>
        <Router>
            <Switch>
                {/* Public routes */}
                <Route exact path="/" component={Home} />
                <Route exact path="/login" component={Login} />

                {/* Private routes */}
                <PrivateRoute exact path="/profile" component={Profile} />
                <PrivateRoute exact path="/profile/articles" component={ArticlesList} />
                <PrivateRoute exact path="/profile/articles/new" component={ArticleForm} />
                <PrivateRoute exact path="/profile/articles/:id(\d+)" component={ArticleForm} />
            </Switch>
        </Router>
    </Provider> 
);

export default App;

这是我的userActions.js的一部分,其中定义了身份验证操作

export const auth = () => async dispatch => {
    dispatch({ type: AUTH_USER_REQUEST });

    try{
        let data = await UserService.auth();

        dispatch({
            type: AUTH_USER_SUCCESS,
            payload: data
        });
    }catch(err){
        dispatch({
            type: AUTH_USER_ERROR,
            payload: err.message
        });
    }
}

我的一个想法是创建一个父 Route 类来进行路由,并在auth那里调用。

标签: reactjsreduxmiddleware

解决方案


为了克服它,我使用 Redux 做了如下的事情:

<Switch>
  <Route 
    path="/"
    component={this.props.auth.authenticationInProgress ? BlankPage : 
      (this.props.auth.isAuthenticated ? SegmentPage : LoginPage)}
    exact={true}
  />
  <Route component={NotFoundPage}/>
</Switch>

如果用户登录,Route 会呈现 SegmentPage。否则它会呈现 LoginPage。一旦触发登录或注销过程,就会切换身份验证并相应地呈现页面。我还保留了身份验证过程的状态,以便在身份验证检查期间不会向用户显示私人数据。


推荐阅读