jueves, 8 de agosto de 2019

React Router v4 Tutorial - #4 Switch, Redirect, & Fallback Routes

If you send out a request to a gibberish URL, how'd you expect the web app to respond? Typically, a website would either spit back a 404 Not Found template, or first redirect to a dedicated page (e.g. /404) and then display the Not Found message. Sounds sensible, but where does React Router come in?

To make a redirect, you can use the Redirect component. When returned from then render() method, it will navigate to the new location specified under the "to" prop. Note that by default, Redirect simulates an HTTP (i.e. server) redirect in that it replaces the current location with a given path, thereby clearing the originating page from the history stack.

Alternatively, you could also redirect programatically. The history object provides two methods to achieve that, push() and replace(). history.push() pushes a new entry to the browser history stack (hence the name) and navigates to the new page (same as if you were to set location.href with vanilla JavaScript). Keep in mind that this approach is identical to clicking the link yourself in that the session history is left intact, so the user could still use the "Back" button to go back to the previous page.

At times, your business logic requires that the user does not have an option to navigate back in the history. For instance, when placing an online order, your customers shouldn't generally be able to return to a previous step and re-submit the form. This would entail a hard redirect that clears the current page from the history stack, and that's where history.replace() shines. Similarly to the Redirect component, replace() replaces the current history entry (hence the name, once again), so the user can't navigate back to it. This approach emulates a server redirect and can also done with location.replace() in vanilla JS.


No hay comentarios:

Publicar un comentario