Typescript 路由器中不工作的路由

Typescript 路由器中不工作的路由,typescript,react-router,electron,Typescript,React Router,Electron,我可能很容易做错事,我没有看到,但我已经尝试了三种方法,但都不起作用 我有一个TypeScript Electron(这是无关的)应用程序,它使用react-redux,react-router,react-router-dom,以及redux-observeable。我不认为这是密切相关的,但我不能得到我的路线更新 我知道有三种方法可以一次访问history.push 从上下文中获取它。我知道这很糟糕 在创建历史时和导入历史之前导出历史。(不喜欢这个,它看起来不太地道) 使用路由器和Rout

我可能很容易做错事,我没有看到,但我已经尝试了三种方法,但都不起作用

我有一个TypeScript Electron(这是无关的)应用程序,它使用
react-redux
react-router
react-router-dom
,以及
redux-observeable
。我不认为这是密切相关的,但我不能得到我的路线更新

我知道有三种方法可以一次访问
history.push

  • 上下文中获取它。我知道这很糟糕
  • 在创建历史时和导入历史之前导出历史。(不喜欢这个,它看起来不太地道)
  • 使用路由器
    RouteComponentProps
    接口
第一种方法是不稳定的,看起来很粗糙。后两者都会导致相同的问题。确实会发生位置更改事件,但由于
推送
失败,并且当
道具
更改时,我正在进行位置更改(我不喜欢此解决方案本身,但某些内容将侦听状态更新,无论它是否为“容器组件”),因此进入无限循环(直到路由器放弃)因为路由从未真正更新

例如,我在
redux记录器中看到了这一点:

{
  type: "@@router/LOCATION_CHANGE", 
  payload: {
   hash:"",
   pathname:"/home"
   ...
  }
  ...
}
这是正确的,但它实际上从未改变路线

这是我的
Routes.tsx
文件:

export default () => (
  <App>
    <Switch>
      <Route path="/" component={LoginPage} />
      <Route path="/home" component={HomePage} />
    </Switch>
  </App>
);
对于grins,这里是试图触发路由更改的组件,在这种情况下,当用户已通过身份验证时:

interface Props { }

interface InjectedProps extends RouteComponentProps<InjectedProps>{
  auth: AuthState
}

const mapStateToProps = (state: AppState): Props => ({
  auth: state.auth
});

export class LoginPage extends React.Component<RouteComponentProps<InjectedProps>> {
  constructor(props: RouteComponentProps<InjectedProps>) {
    super(props);
  }

  injectedProps(): InjectedProps {
    return this.props as InjectedProps;
  }

  componentWillReceiveProps(newProps: InjectedProps) {
    if(newProps.auth.authenticated) {
     this.props.history.push('/home');
    }
  }

  render() {
    return (
      <Login />
    );
  }
}

export default withRouter(connect(mapStateToProps)(LoginPage));
interface Props{}
接口注入Props扩展了RouteComponentProps{
auth:AuthState
}
常量mapStateToProps=(状态:AppState):Props=>({
auth:state.auth
});
导出类LoginPage扩展React.Component{
构造函数(道具:RouteComponentProps){
超级(道具);
}
injectedProps():injectedProps{
将this.props作为InjectedProps返回;
}
组件将接收道具(新道具:注入道具){
if(newProps.auth.authenticated){
this.props.history.push('/home');
}
}
render(){
返回(
);
}
}
使用路由器导出默认值(connect(mapstatetops)(LoginPage));
诚然,作为一个整体,我仍然习惯于TS/Redux(这可能是某种反模式),但在一个普通的React web应用程序中使用
push
从来没有遇到过问题

如果您对如何更好地构建这样一个应用程序有任何其他建议,我洗耳恭听。理想情况下,我希望有一个action creator启动这样的导航更改,这样我就可以保持组件的轻量级。

嗯,修复非常简单

我只是不得不改变路线。我不完全明白为什么这样做有效,这很麻烦

export default () => (
  <App>
    <Switch>
      <Route path="/home" component={HomePage} />
      <Route path="/" component={LoginPage} />
    </Switch>
  </App>
);
导出默认值()=>(
);

精确路径=
模式也有效…我没有意识到的是
“/”
“/home”
是子集匹配。请参阅
export default () => (
  <App>
    <Switch>
      <Route path="/home" component={HomePage} />
      <Route path="/" component={LoginPage} />
    </Switch>
  </App>
);