【发布时间】:2018-09-30 09:25:13
【问题描述】:
我很容易做一些我看不到的错误,但我尝试了三种方法,但都没有成功...
我有一个使用 react-redux、react-router、react-router-dom 和 redux-observable 的 TypeScript Electron(这无关紧要)应用程序。我不认为大部分是密切相关的,但我无法让我的路线更新......
我知道有三种方法可以获得对history.push 的一次访问。
- 从
context获取。 我知道这很糟糕。 - 在我创建历史记录时和在我导入它之前导出它。 (不喜欢这个,它似乎不惯用)
- 利用
withRouter和RouteComponentProps接口。
第一种方法,不稳定,看起来很老套。后两者都导致相同的问题。确实发生了位置更改事件,但是因为 push 失败并且我在 props 更改时进行位置更改(我本身不喜欢这个解决方案,但是 something 会正在监听状态更新,无论它是否是“容器组件”)它进入一个无限循环(直到路由器放弃),因为路由从不实际更新。
例如我在redux-logger 看到这个:
{
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>
);
像这样被拉入index.tsx:
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if ((module as any).hot) {
(module as any).hot.accept('./containers/Root', () => {
const NextRoot = require('./containers/Root').default;
render(
<AppContainer>
<NextRoot store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
});
}
而且,对于咧嘴笑,这里是试图触发路由更改的组件,在这种情况下,当用户已通过身份验证时:
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));
当然,我仍然习惯于整体上使用 TS/Redux(这可能是一种反模式),但我在使用 push 时从未遇到过问题普通的旧 React Web 应用程序。
如果您对更好地构建这样的应用程序有任何其他建议,我会全力以赴。理想情况下,我希望让动作创建者触发此类导航更改,这样我就可以保持组件的轻量级。
【问题讨论】:
标签: typescript react-router electron