A veces he visto a personas envolver sus componentes con withRouter cuando los están exportando:
import { withRouter } from 'react-router-dom'; class Foo extends React.Component { // ... } export default withRouter(Foo);¿Para qué es esto y cuándo debo usarlo?
Cuando incluye un componente de página principal en su aplicación, a menudo se envuelve en un componente <Route> como este:
<Route path="/movies" component={MoviesIndex} /> Al hacer esto, el componente MoviesIndex tiene acceso a this.props.history para que pueda redirigir al usuario con this.props.history.push .
Algunos componentes (comúnmente un componente de encabezado) aparecen en cada página, por lo que no están envueltos en una <Route> :
render() { return (<Header />); }Esto significa que el encabezado no puede redirigir al usuario.
Para solucionar este problema, el componente de encabezado se puede envolver en una función withRouter , ya sea cuando se exporta:
export default withRouter(Header) Esto le da acceso al componente Header a this.props.history , lo que significa que el encabezado ahora puede redirigir al usuario.
withRouter es un componente de orden superior que pasará la match de la ruta más cercana, la location actual y los accesorios del history al componente envuelto siempre que se represente. simplemente conecta el componente al enrutador.
No todos los componentes, especialmente los componentes compartidos, tendrán acceso a los accesorios de dicho enrutador. Dentro de sus componentes envueltos, podrá acceder a la propiedad de location y obtener más información como location.pathname o redirigir al usuario a una URL diferente usando this.props.history.push .
Aquí hay un ejemplo completo de su página de github:
import React from "react"; import PropTypes from "prop-types"; import { withRouter } from "react-router"; // A simple component that shows the pathname of the current location class ShowTheLocation extends React.Component { static propTypes = { match: PropTypes.object.isRequired, location: PropTypes.object.isRequired, history: PropTypes.object.isRequired }; render() { const { match, location, history } = this.props; return <div>You are now at {location.pathname}</div>; } } // Create a new component that is "connected" (to borrow redux // terminology) to the router. const ShowTheLocationWithRouter = withRouter(ShowTheLocation);Se puede encontrar más información aquí .
El componente de orden superior withRouter le permite obtener acceso a las propiedades del objeto de history y la coincidencia de <Route> más cercana. withRouter pasará accesorios actualizados de match , location e history al componente envuelto siempre que se represente.
import React from "react"; import PropTypes from "prop-types"; import { withRouter } from "react-router"; // A simple component that shows the pathname of the current location class ShowTheLocation extends React.Component { static propTypes = { match: PropTypes.object.isRequired, location: PropTypes.object.isRequired, history: PropTypes.object.isRequired }; render() { const { match, location, history } = this.props; return <div>You are now at {location.pathname}</div>; } } // Create a new component that is "connected" (to borrow redux // terminology) to the router. const ShowTheLocationWithRouter = withRouter(ShowTheLocation);