Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.2K
Views
¿Para qué sirve withRouter en react-router-dom?

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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í .

over 4 years ago · Santiago Trujillo Report

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!