react-router Redirect vs history.push

断了今生、忘了曾经 提交于 2019-12-04 16:54:15

问题


I was reading react-router-redux examples and I confused, what is the difference beetween:

import { Redirect } from 'react-router-dom'

...

<Redirect to='/login' /> 

and

import { push } from 'react-router-redux'

...

push('/login')

回答1:


Redirect

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

whereas History

push function Pushes a new entry onto the history stack




回答2:


The <Redirect> component will, by default, replace the current location with a new location in the history stack, basically working as a server-side redirect.

But it can also be used with the property push and in this case it will push a new entry into the history stack, working the same way as history.push.

In fact the <Redirect> component uses the history push and replace methods behinds the scene. It is just a more React way of navigating.

So basically you have two ways of navigating:

  1. Use the history.push and history.replace in a component (usually wrapped with the withRouter HOC, so that you can have access to the location object without having to pass it from parent to child.

  2. Use the <Redirect> component with or without the push property, depending



来源:https://stackoverflow.com/questions/48619733/react-router-redirect-vs-history-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!