Reactjs React路由器v4等待xhr身份验证转换到路由

Reactjs React路由器v4等待xhr身份验证转换到路由,reactjs,react-router,Reactjs,React Router,我试图在使用React Router v4时实现一些服务器端身份验证(通过xhr)。我不希望路由转换,直到我与我的服务器确认用户已通过身份验证(通过使用令牌),并且令牌存储在会话存储中(不需要异步) 目前的问题是,即使用户未经身份验证,我的“私有”路由仍在尝试呈现 我的路由器路由如下所示: class AppContainer extends Component { render() { return ( <div> <main>

我试图在使用React Router v4时实现一些服务器端身份验证(通过xhr)。我不希望路由转换,直到我与我的服务器确认用户已通过身份验证(通过使用令牌),并且令牌存储在会话存储中(不需要异步)

目前的问题是,即使用户未经身份验证,我的“私有”路由仍在尝试呈现

我的路由器路由如下所示:

class AppContainer extends Component {
  render() {
    return (
      <div>
        <main>
          <Switch>
            <Route exact path='/' component={Home} />
            <PrivateRoute path='/dashboard' component={Dashboard} />
          </Switch>
        </main>
      </div>
    );
  }
}

即使用户未通过身份验证,仪表板仍在尝试呈现。如何等待api调用返回,然后将用户重定向到
/dashboard
/
(主页)?

我的上一次尝试您可以使用如下组件:

import React, {PropTypes} from 'react';
import {Redirect} from 'react-router-dom';
export default class PrivateRoute extends React.Component {
  constructor(props) {
    super(props);
    this.state={loading:true,authenticated:false}
  }
  componentDidMount(){
    /* your authentication logic...*/
    setTimeout(()=>{
      this.setState({loading:false,authenticated:true});
    },3000)
  }
  render() {
    if(this.state.loading)
    return <h1>Loading</h1>;

    if(this.state.authenticated)
    return (this.props.children);
    else
    return <Redirect to="/" />
  }
}
<Route path="/your-protected-route" component={()=><PrivateRoute><YourComponent /></PrivateRoute>} />
import React,{PropTypes}来自'React';
从'react router dom'导入{Redirect};
导出默认类PrivateRoute扩展React.Component{
建造师(道具){
超级(道具);
this.state={loading:true,authenticated:false}
}
componentDidMount(){
/*您的身份验证逻辑*/
设置超时(()=>{
this.setState({loading:false,authenticated:true});
},3000)
}
render(){
if(this.state.loading)
回装;
if(this.state.authenticated)
返回(本.道具.儿童);
其他的
返回
}
}
并在路由器中使用它,如下所示:

import React, {PropTypes} from 'react';
import {Redirect} from 'react-router-dom';
export default class PrivateRoute extends React.Component {
  constructor(props) {
    super(props);
    this.state={loading:true,authenticated:false}
  }
  componentDidMount(){
    /* your authentication logic...*/
    setTimeout(()=>{
      this.setState({loading:false,authenticated:true});
    },3000)
  }
  render() {
    if(this.state.loading)
    return <h1>Loading</h1>;

    if(this.state.authenticated)
    return (this.props.children);
    else
    return <Redirect to="/" />
  }
}
<Route path="/your-protected-route" component={()=><PrivateRoute><YourComponent /></PrivateRoute>} />
}/>

是的,像这样的东西当然可以工作,尽管我希望用React路由器能有一种更易于维护的方式。一旦我获得了多条路由(公共和私有),管理它可能会有点麻烦。谢谢你的建议!您可以使用Mobx或Redux在所有组件之间共享状态,这样做添加Mobx/Redux将无助于解决此问题。问题不是状态管理,而是管理多条路由,这些路由可以是私有的,也可以是公共的。