React Router重定向到Login页面但不呈现Login组件

时间:2017-09-04 12:13:23

标签: reactjs react-router

我正在使用React Router v4进行非常基本的身份验证工作流程,如下所示:

const AuthenticatedRoute = ({ component: Component, ...rest }) => (  
  <Route {...rest} render={props => (
    sessionStorage.getItem('jwt') ? (
      <Component {...props} />
    ) : (
      <Redirect to={{
        pathname: "/login",
        state: { from: props.location }
      }} />
    )
  )}/>
)

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
          <AuthenticatedRoute exact path="/" component={App}  />
          <Route path="/login" component={LoginPage} />
      </div>
    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

当没有&jwt&#39; jwt&#39;应用程序重定向到/ login。然而,奇怪的是,直到我从浏览器按下刷新才会呈现(即空白页面)。

不确定如何调试和/或可能出现的问题,因为这是与在线发现的大多数示例类似的方法。

2 个答案:

答案 0 :(得分:2)

我猜你使用react-redux,这是一个常见的问题。 (如果不是,我会删除答案)

在react-redux {pure: false}中使用connect或使用withRouter HOC。

React router 4 does not update view on link, but does on refresh

答案 1 :(得分:0)

我来这里时遇到了同样的问题。我的流程涉及产品详细信息页面中的模式弹出窗口,单击确定按钮将执行某些任务,并将用户带回产品列表页面。尝试过{pure: false}withConnect(connect...。也尝试了其他几件事。没事。然后最简单的事情起作用了。我用this.setState({showConfirmationModal: true});打开了模态,因此在.then的{​​{1}}的successHandler中,我用axios.get将其关闭,然后使用state属性来呈现<{{ 1 {}中的1}}。有效 !!。希望这会有所帮助。