Updating Store Before Custom Route

谁都会走 提交于 2020-01-06 05:30:08

问题


I am designing react application with node server. I have created a custom Private Route

import React from 'react';
import {connect} from 'react-redux';
import {Route, Redirect} from 'react-router-dom';

class PrivateRoute extends React.Component{
    render() {
        const { isAuthenticated, component: Component, ...rest } = this.props;

        return (
            <Route {...rest} component={(props) => {
                if(isAuthenticated){
                    return <Component {...props}/>
                }
                else{
                    return <Redirect to="/login" />
                }
            }}/>
        )
    }
}

const mapStateToProps = (state) => {
    return{
        isAuthenticated: state.auth.email !== '' ? true : false
    }
}

const ConnectedPrivateRoute = connect(mapStateToProps)(PrivateRoute)
export default ConnectedPrivateRoute;

I am redirecting myself to dashboard route from node serer after login.

import React from 'react';
import axios from 'axios';
import {connect} from 'react-redux';
import { setAuthenticatedUser } from '../actions/authA';

class Dashboard extends React.Component{
  constructor(props) {
    super(props);
    axios.get('/cookie').then((user) => {
      if(user.data.email)
        this.props.dispatch(setAuthenticatedUser(user.data));
    })
    .catch((e) => {
      console.log("Got some error");
    })
  }
  render() {
    return (
      <div>Dashboard Page</div>
    );
  }
}

export default connect()(Dashboard);

Currently my dashboard looks for cookie about authentication and update my store.But after adding custom route there happens a redirection to login page that's because my custom route doesnot find the updated store since it is updated in dashboard. I am stuck here. I tried updating in my custom route but I added more confusion to myself. Any suggestion and solution is appreciated.

Thanks


回答1:


If you post your Login component, I could better answer the question.

Having said that, it is not the responsibility of the dashboard component to setAuthenticatedUser, since, if they are able to navigate to the dashboard, it means they are ALREADY authenticated.

After a user logs in, you should call setAuthenticatedUser, then redirect to the dashboard, that way your PrivateRoute component won't force a needless redirect.



来源:https://stackoverflow.com/questions/52014863/updating-store-before-custom-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!