在使用本地存储和react-redux重定向到登录页面之前,如何检查用户是否已登录?

时间:2019-04-26 07:02:56

标签: reactjs react-redux react-router local-storage

我正在使用HOC进行经过身份验证的路由。我想在重定向到登录页面之前检查本地存储中是否有登录用户,但是在应用加载时,它首先会重定向,然后再登录本地存储。

App.js

class App extends Component {
  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <Route render={({ history }) => (
            <div className="App">
              <Navbar currUser={this.props.currUser} logout={this.props.logout} history={history}/>
              <Switch>
                <Auth 
                    exact path="/" 
                    component={HomePage} 
                    currUser={this.props.currUser} 
                    loadRecipes={this.props.loadRecipes} 
                    recipes={this.props.recipes} 
                />
                <Route
                    path="/login" 
                    render={(props) => (<LoginPage {...props} login={this.props.login} />)}
                />
              </Switch>
            </div>
          )} />
        </BrowserRouter>
      </div>
    );
  }
}

const Auth = ({ component: Component, ...rest }) => {
  const currUser = rest.currUser;
  return (
    <Route {...rest} render=
      {props =>
        currUser ?
          (<Component {...props}  {...rest} />) :
          (<Redirect to={{ pathname: "/login", state: currUser }} />)
      } />
  )
}


const mapStateToProps = (state) => {
  return {
    currUser: state.login.currUser,
    recipes: state.recipe.recipes,
    recipe: state.recipe.recipe,
    user: state.user.userToDisplay,
  }
}

const mapDispatchToProps = {
  ...loginActions,
  ...recipeActions,
  ...userActions
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

LoginActions.js

export const login = (credentials) => {
    return async (dispatch) => {
        try {
            const user = await UserService.login(credentials);
            dispatch({ type: 'SET_CURR_USER', user })
            return true;
        } catch (err) {
            return false
        }
    }
}

UserService.js

async function login(credentials) {
    try {
        const { data } = await axios.post(`${BASE_URL}/login`, credentials);
        StorageService.saveToLocal(USER_KEY, data);
        return data;
    } catch (err) {
        throw err;
    }
}

我该怎么做才能使该应用程序首先检查是否存在登录用户,如果没有,则重定向?

谢谢!

编辑:

LoginReducer.js

const loginReducer = (state = {
    currUser: ''
}, action) => {
    switch (action.type) {
        case 'SET_CURR_USER':
            return {
                ...state,
                currUser: action.user
            }
        default:
            return state;
    }
}

export default loginReducer;

StorageService.js

export default {
    getFromLocal,
    saveToLocal,
    removeFromLocal
}
function getFromLocal(key) {
    const res = localStorage.getItem(key)
    return res ? JSON.parse(localStorage.getItem(key)) : null
}
function saveToLocal(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
}

function removeFromLocal(key) {
    localStorage.removeItem(key);
}

身份验证中当前用户的日志:

  • 第一(加载应用程序时)-currUser:”
  • 登录并重定向到主页后-currUser:{_id:“ 5cc15863d1a9f045fcbd6d85”,名称:“ amanda”}

0 个答案:

没有答案