代码之家  ›  专栏  ›  技术社区  ›  Steve Clay

在React中,渲染重定向总是比使用重定向更好。道具。历史推

  •  11
  • Steve Clay  · 技术社区  · 7 年前

    如果我总是重定向到应用内路由,那么 Redirect react路由器dom(v4)中的组件,以及 this.props.history.push()

    /foo/123 /foo/123/some-title (均使用相同的管线/组件渲染)。

    我看到了 重新使用 进入状态。这会在哪里结束?

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

    save() {
      this.setState({ redir: '/new-path'; });
    }
    ...
    render () {
      if (this.state.redir) {
        return <Redirect to={this.state.redir} />;
      }
      ...
    }
    
    1 回复  |  直到 7 年前
        1
  •  6
  •   Maru    7 年前

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

    所以问题是 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 history.push() 在里面 组件C

    Redirect 本应是react路由器维护人员提供的场景的答案,但有些人根本不喜欢这个想法(包括我)。


    从功能上讲,两者在功能上似乎没有重大差异 重新使用 history.push 因为Redirect在引擎盖下使用它。使用历史重定向的主要原因。推动这一点的是,如果历史如何运作,或者他们决定在以后以不同的方式处理上下文,则重定向是未来的证明。