Reactjs 反应路由器竞争条件

Reactjs 反应路由器竞争条件,reactjs,redux,react-router,Reactjs,Redux,React Router,我有一个dom和redux。我的情况很简单: 1) 如果用户没有令牌,则重定向到登录 2) 否则,请转到仪表板。 问题是,令牌的redux检查(在本地存储中)晚了一点到达,所以无论我做什么,我都会重定向到login 代码: const asyncouth=asyncomponent(()=>import('containers/Auth/Auth'); const AsyncDashboard=asyncComponent(()=>import('containers/Dashboard/Das

我有一个dom和redux。我的情况很简单: 1) 如果用户没有令牌,则重定向到登录 2) 否则,请转到仪表板。 问题是,令牌的redux检查(在本地存储中)晚了一点到达,所以无论我做什么,我都会重定向到login

代码:

const asyncouth=asyncomponent(()=>import('containers/Auth/Auth');
const AsyncDashboard=asyncComponent(()=>import('containers/Dashboard/Dashboard');
接口IProps{
自动签名:()=>无效;
未验证:布尔值;
}
类应用程序扩展了React.Component{
公共组件didmount(){
this.props.autoSignIn();
}
公共渲染(){
返回(
{this.props.isAuthenticated&&}
);
}
}
常量mapStateToProps=(状态:任意)=>({
isAuthenticated:state.auth.idToken!==null
});
const mapDispatchToProps=(调度:任意)=>({
自动签名:()=>分派(authAutoSignIn())
});
导出默认连接(mapStateToProps、mapDispatchToProps)(应用程序);

您没有发布redux代码,但我假设您的
自动签名
操作创建者执行异步操作。您可以做的是在缩减器中保存
状态。auth
保留一些状态,如
triedAutoLogin:false


无论何时异步登录操作解决(成功/失败),您都可以更新
triedAutoLogin:true
。然后将其包含在
MapStateTrops
中,并根据这两个属性有条件地呈现
组件。

使用redux thunk(和通量标准操作)时的一个常见模式是具有
requestStatus
属性

它通常用于HTTP请求,您将有
NotStarted
,“Initiated”,“Success”和“Failed”

您可以将类似的样式应用于Redux

您可以具有具有相同值的
authCheckStatus
属性

在组件中,当
authCheckStatus
不是
Success
时,不渲染路由器,而是渲染其他内容(如果检查足够快,则不渲染任何内容)


这将与
idToken
本身分开。

不,另一端的sync:[link]不正确,因为在state.auth.idToken上,isAuthenticated默认为false!==无效的
const AsyncAuth = asyncComponent(() => import('containers/Auth/Auth'));
const AsyncDashboard = asyncComponent(() => import('containers/Dashboard/Dashboard'));
interface IProps {
  autoSignIn: () => void;
  isAuthenticated: boolean;
}
class App extends React.Component<IProps, {}> {

  public componentDidMount() {
    this.props.autoSignIn();
  }

  public render() {
    return (
      <div>
        <Switch>
          <Route path="/auth" component={AsyncAuth} />
          {this.props.isAuthenticated && <Route path="/dashboard" component={AsyncDashboard} />}
          <Redirect to="/auth" />
        </Switch>
      </div>
    );
  }
}

const mapStateToProps = (state: any) => ({
  isAuthenticated: state.auth.idToken !== null
});

const mapDispatchToProps = (dispatch: any) => ({
  autoSignIn: () => dispatch(authAutoSignIn())
});

export default connect(mapStateToProps, mapDispatchToProps)(App);