React Router:无法访问专用路由

时间:2020-11-02 17:26:28

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

我没有得到我想要的帮助。我在下面的代码中添加了更多信息。我有一条受保护的路由,只有在用户登录后将isAuthenticated设置为true时,才能访问该路由。我遇到的问题是,即使成功登录并通过身份验证后,我仍被重定向到登录页面。在下面的redux reducer文件中,默认将isAuthenticated状态设置为null。奇怪的是,如果我将isAuthenticated默认值设置为true,然后成功登录,则可以访问受保护的路由。但是,将isAuthenticated设置为null时,即使我成功登录,也无法访问受保护的路由。如果有人可以帮助,将不胜感激。谢谢。

//加载用户操作文件

export const loadUser = () => (dispatch, getState) =>{

  dispatch({type: USER_LOADING});
  const token = getState().auth.token; 
 
  const config = {
    headers:{
      "Content-Type": "application/json"
    }
  }

if(token){
  config.headers['x-authorization'] = token;
}

  axios.get('/api/user/', config)
    .then(res => dispatch({
      type: USER_LOADED,
      payload: res.data
    }))
    .catch(err => {
      dispatch(returnErrors(err.response.data, err.response.status));
      dispatch({
        type: AUTH_ERROR
      });
    });
  };

// Redux Reducer文件

import{
  LOGIN_FAIL,
  LOGIN_SUCCESS,
  USER_LOADING,
  USER_LOADED,
  AUTH_ERROR
} from '../actions/types';

const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: null,
  isLoading: false,
  user: null
};

export default function(state = initialState, action){
  switch(action.type){
    case USER_LOADING:
      return{
        ...state,
        isLoading: true
      };
    case USER_LOADED:
      return{
        ...state,
        isAuthenticated: true,
        isLoading: false,
        user: action.payload
      };
    case LOGIN_SUCCESS:
    localStorage.setItem('token', action.payload.token);
    return{
      ...state,
      ...action.payload,
      isAuthenticated: true,
      isLoading: false
    };
    case LOGIN_FAIL:
    case AUTH_ERROR:
    localStorage.removeItem('token');
      return{
        ...state,
        token: null,
        isAuthenticated: false,
        isLoading: false,
        user: null
      };

    default:
      return state;
  }

}

//受保护的路由文件

export const ProtectedRoute = ({
  isAuthenticated,
  component: Component,
  ...rest
})=>(
  <Route {...rest} component={(props) =>(
    isAuthenticated ? (
      <Component {...props}/>
    ):(
      <Redirect to="/login"/>
    )
  )}/>

)

ProtectedRoute.propTypes = {
  isAuthenticated: PropTypes.bool
}
const mapStateToProps = state =>({
  isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps)(ProtectedRoute)

// App.js文件

class App extends Component{
  componentDidMount(){
    store.dispatch(loadUser());
  }
  render(){
  return(
  <Provider store={store}>
  <div className="App">
    <Router>
      <Switch>
        <Route exact path="/login" component={LoginPage}/>
        <ProtectedRoute exact path="/userfeed" component={UserFeed}/>
      </Switch>
    </Router>
  </div>
  </Provider>

);
}
};

export default App;

0 个答案:

没有答案