React Router-基于身份验证的重定向

时间:2018-12-02 19:44:58

标签: reactjs redux react-redux react-router react-router-v4

我正在构建一个登录页面示例,以提高我的反应能力。但是,我不知道有关React Router的问题。我成功通过身份验证,应用程序将我带到受保护的页面,但是当我在此受保护的页面中刷新页面时,它显示空白页面。

当我尝试手动编写受保护的URL时,也会发生同样的事情。 (黑屏)

这是PrivateRoute

    export const PrivateRoute = ({ 
        isAuthenticated, 
        component: Component,
        ...rest  
    }) => (
       <Route {...rest} render={(props) => {
           if (isAuthenticated) {
               return <Component {...props} />
        }
        else {
            return <Redirect to="/" />
        }

    }} />
);

const mapStateToProps = state => {
    console.log(state.userReducer.token);
    return {
        isAuthenticated: !!state.userReducer.token
    }
};

export default connect(mapStateToProps)(PrivateRoute);

这是PublicRoute

export const PublicRoute = ({ isAuthenticated, component: Component,  ...rest}) => (
    <Route {...rest} render={(props) => {
        if (isAuthenticated) { 
          return <Redirect to="/logged" /> 
        }
        else {
          return <Component {...props} />
        }
    }} />
  );

const mapStateToProps = state => ({
  isAuthenticated: !!state.userReducer.token
});

export default connect(mapStateToProps)(PublicRoute);

AppRouter

const AppRouter = () => {
    return (
    <BrowserRouter>
        <div>
            <PublicRoute path="/" component={LoginForm} exact />
            <PrivateRoute path="/logged" component={LoggedPage} />
        </div>
    </BrowserRouter>
    );
}
export default AppRouter;

最后是我创建的AppRouter的最后一个

const  jsx = (
    <Provider store={createStore(reducers)}>
        <AppRouter />
    </Provider>
)
ReactDOM.render(jsx, document.getElementById('root'));

我很感谢您的建议,谢谢您

1 个答案:

答案 0 :(得分:0)

页面刷新时,它会丢失其状态以及您的登录状态。您应该将一些数据放入本地存储以保留会话信息。在调度有关登录的操作之前,我将用户凭据保存到本地存储中。 每当页面重新加载时,我都会从本地存储中获取数据并将其作为登录操作进行分发。所以我保持会议开放。

export function signInUser(user) {
  let userEmail = user.email;
  let userPassword = user.password;
  let credentials = {
    email: userEmail,
    password: userPassword
  };
  return dispatch => {
    axios
      .request({
        method: "post",
        url: loopBack + "/blogusers/login?include=user",
        data: credentials
      })
      .then(response => {
        //sets user data to local storage
        localStorage.setItem("id", response.data.id);
        localStorage.setItem("userId", response.data.userId);
        localStorage.setItem("userName", response.data.user.userName);
        localStorage.setItem("email", response.data.user.email);
        return dispatch(signInSuccess(response.data));
      })
      .catch(error => {
        return dispatch(signInFailure(error));
      });
  };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

//if session information is lost it gets data from            localstorage and set user data
export function setToken() {
   return dispatch => {
    let id = localStorage.getItem("id");
    let userId = localStorage.getItem("userId");
    let userName = localStorage.getItem("userName");
    let email = localStorage.getItem("email");
    let user = { id, userId, user: { email, userName } };
    return dispatch(signInSuccess(user));
  };
}