In React is it always better to render a Redirect than use this.props.history.push?

后端 未结 1 1843
感情败类
感情败类 2021-01-17 20:09

If I\'m always redirecting to in-app routes, what\'s the difference between the Redirect component in react-router-dom (v4), and this.props.history.push()

相关标签:
1条回答
  • 2021-01-17 20:19

    I am someone who is sternly against rendering redirects as it is kind of counterintuitive that you have to render a component in order to change the page however it does provide some clear benefits

    so the issue with this.props.history.push() is mostly when you are dealing with child components that are triggering redirects

    Component A # the one Rendered by the Route
      Component B
        Component C # the one triggering the redirect
    

    in the example above, unless you are diligent with passing down the route props from Component A down to Component C, then you wouldn't be able to use history.push() in Component C

    Rendering Redirect was supposed to be the answer to that scenario that was provided by the maintainer of react-router but some people just dont like the idea at all(me included).


    Functioanally speaking, there doesnt seem to be major differences in functionality between Redirect and history.push as Redirect uses it under the hood. The major reason to use Redirect over history.push is that Redirect is future proofed from possible changes on how history would work or if they decide to handle context differently at a later date.

    0 讨论(0)
提交回复
热议问题