【问题标题】:In React is it always better to render a Redirect than use this.props.history.push?在 React 中,渲染重定向总是比使用 this.props.history.push 更好吗?
【发布时间】:2018-03-27 05:29:15
【问题描述】:

如果我总是重定向到应用内路由,react-router-dom (v4) 中的Redirect 组件和this.props.history.push() 有什么区别?

例如假设我想在 URL 中添加一个用户给定的标题并从 /foo/123 重定向到 /foo/123/some-title(两者都使用相同的路由/组件呈现)。

我看到Redirect 的某些用法传入状态。这会在哪里结束?

在状态中指定要重定向到的位置是一种反模式吗?为什么示例代码看起来不像这样:

save() {
  this.setState({ redir: '/new-path'; });
}
...
render () {
  if (this.state.redir) {
    return <Redirect to={this.state.redir} />;
  }
  ...
}

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    我是一个强烈反对渲染重定向的人,因为您必须渲染一个组件才能更改页面有点违反直觉,但它确实提供了一些明显的好处

    所以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,否则你将无法在Component C中使用history.push()

    渲染 Redirect 应该是 react-router 维护者提供的那个场景的答案,但有些人根本不喜欢这个想法(包括我)。


    从功能上讲,Redirecthistory.push 之间的功能似乎没有重大差异,因为 Redirect 在后台使用它。使用 Redirect 而不是 history.push 的主要原因是,Redirect 可以应对未来可能发生的历史变化,或者他们决定在以后以不同的方式处理上下文。

    【讨论】:

    • 通过使用withRouter 包装您的组件,您可以访问任何层次结构级别的路由器道具
    • @ShubhamKhatri 是的,只要使用 withRouter 作为 HOC 的组件仅将历史记录用于推送,那么就不会有问题。就我而言,我尝试从使用 withRouter 的组件中访问 match,但没有得到我想要的结果
    • 那么 Redirect 在后台使用 history.push 吗?我想知道理想情况下的行为差异。
    • 文档根本没有提到状态。
    • 是的,Redirect 在后台使用history.push。除了Redirect 未来可能会发生对contexthistory 对象的任何更改之外,我看不出两者之间有任何重大的行为差异
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2011-04-08
    • 2018-12-27
    • 2020-11-14
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多