首页 文章

使用Component外部的react-router-dom / react-router v4重定向页面

提问于
浏览
0

我有React-Redux应用程序,应该为服务器返回的所有错误编写一个常见的错误处理程序 . 目前我使用'react-router-dom'进行路由 . 我在组件中使用'withRouter' . 但是我可以重定向内部动作吗?或者如何实现这一目标?

我看到链接How to push to History in React Router v4? . 我应该使用react-router-redux吗?或者可以使用react-router-dom完成此操作 . 有人可以帮忙吗?

export function loginDetails(details) {   
return function (dispatch,getState) { 
    gateway.loginUser(details.username, details.password).then(
        response => {
          dispatch({type: AUTH_USER});             
          dispatch(fetchCompanies());              
      },
       error =>{
           handleError(error, dispatch);               
       })
}
}

handleError = (error, dispatch) =>{    
switch(error.response.status){
    case XX: 
        //Want to redirect to '/' here           
        break;
    case YY:    
        //Want to redirect to '/login' here        
        break;
    default:          
        break;
}
}

1 回答

  • 0

    你在用什么组件?例如,如果有人没有登录,我只会检查mapStateToProps,如果他们没有登录,那么导入并使用react-router-dom的Redirect将它们发送到登录页面

    根据商店的设置方式,它可能如下所示:

    const mapStateToProps = state => ({
           loggedIn: state.auth.user !== null
        })
    

    然后在你正在检查的任何组件中的条件

    if(!loggedIn){
          return <Redirect to="/login" />
        }
    

相关问题