Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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()?

E.g. let's say I want to add a user-given title to the URL and redirect from /foo/123 to /foo/123/some-title (both rendered with same Route/component).

I see in some uses of Redirect passing in state. Where does this end up?

Is it an anti-pattern to specify where you want to redirect to in the state? Why doesn't example code look like this:

save() {
  this.setState({ redir: '/new-path'; });
}
...
render () {
  if (this.state.redir) {
    return <Redirect to={this.state.redir} />;
  }
  ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...