Reactjs React路由器v4和Redux身份验证

Reactjs React路由器v4和Redux身份验证,reactjs,redux,react-router,Reactjs,Redux,React Router,我正在为一个新项目使用react router v4和Redux 我有以下代码: export class App extends Component { componentDidMount() { const { dispatch } = this.props; dispatch(initAuth()); } render() { const { user } = this.props; return ( <BrowserRout

我正在为一个新项目使用react router v4和Redux

我有以下代码:

export class App extends Component {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(initAuth());
  }

  render() {
    const { user } = this.props;
    return (
      <BrowserRouter>
        <div>
          <NavContainer />
          <Match pattern="/login" component={LogInForm} />
          <MatchWhenAuthorized pattern='/users' component={Users} user={user} />
        </div>
      </BrowserRouter>
    );
  }
}
导出类应用程序扩展组件{
componentDidMount(){
const{dispatch}=this.props;
分派(initAuth());
}
render(){
const{user}=this.props;
返回(
);
}
}
其中initAuth调度一个操作,该操作检查本地存储中是否存在令牌,如果存在令牌,还将调度一个登录操作

问题是,如果我直接转到
myapp.com/users
,操作还没有返回,因此没有用户登录,在这种情况下,MatchWhenAuthorized会将我重定向到我的LogInForm,如果我的initAuth登录了用户,我不希望这样

有没有一个优雅的方法来解决这个问题


我想我可以通过仅在有用户登录的情况下呈现
matchwheauthorized
组件来解决这个问题,但这似乎不正确。

初始登录状态应该在页面加载时和安装应用程序之前设置。我不知道为什么
initAuth
是redux操作的创建者,而您可以只检查
localStorage
,而不涉及redux

index.js
然后,您可以将
组件连接到存储,以访问
用户
值,并在存储中没有用户时重定向。

您是否尝试在
组件willmount
中调度initAuth?@vwrobel我尝试过,在第一次渲染时没有区别,用户尚未设置,因此不匹配
import { createStore } from 'redux'
import reducer from './reducer'
import { getUser } from './storage'

// load the user data from localStorage and
// use the value in the store's initial data
const store = createStore(reducer, {
  user: getUser()
})