如果我总是重定向到应用内路由,那么react-router-dom(v4)中的Redirect
组件和this.props.history.push()
之间的区别是什么?
E.g。假设我想在URL中添加用户指定的标题,并从/foo/123
重定向到/foo/123/some-title
(两者都使用相同的Route / component呈现)。
我看到Redirect
传入状态的一些用法。这到底在哪里?
指定要在状态中重定向到的位置是否为反模式?为什么示例代码看起来不像这样:
save() {
this.setState({ redir: '/new-path'; });
}
...
render () {
if (this.state.redir) {
return <Redirect to={this.state.redir} />;
}
...
}
答案 0 :(得分:2)
我是一个严厉反对渲染重定向的人,因为它必须为了更改页面而渲染组件,但它确实提供了一些明显的好处,这是违反直觉的
所以问题this.props.history.push()
主要是在处理触发重定向的子组件时
Component A # the one Rendered by the Route
Component B
Component C # the one triggering the redirect
在上面的示例中,除非您努力将路径道具从Component A
传递到Component C
,否则您将无法在{{1}中使用history.push()
}}
渲染Component C
应该是反应路由器维护者提供的场景的答案,但有些人根本不喜欢这个想法(包括我)。
从功能上讲,Redirect
和Redirect
之间的功能似乎没有太大差异,因为Redirect在引擎盖下使用它。使用Redirect over history.push的主要原因是Redirect将来可以根据历史记录的工作方式进行更改,或者他们是否决定在以后以不同的方式处理上下文。