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

163
Views
Cómo usar Redirect en la versión 5 de react-router-dom de Reactjs

Estoy usando la última versión del módulo react-router, llamado react-router-dom, que se ha convertido en el predeterminado al desarrollar aplicaciones web con React. Quiero saber cómo hacer una redirección después de una solicitud POST. He estado haciendo este código, pero después de la solicitud, no pasa nada. Reviso en la web, pero todos los datos son sobre versiones anteriores del router react, y no con la última actualización.

Código:

 import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { Redirect } from 'react-router' import SignUpForm from '../../register/components/SignUpForm'; import styles from './PagesStyles.css'; import axios from 'axios'; import Footer from '../../shared/components/Footer'; class SignUpPage extends React.Component { constructor(props) { super(props); this.state = { errors: {}, client: { userclient: '', clientname: '', clientbusinessname: '', password: '', confirmPassword: '' } }; this.processForm = this.processForm.bind(this); this.changeClient = this.changeClient.bind(this); } changeClient(event) { const field = event.target.name; const client = this.state.client; client[field] = event.target.value; this.setState({ client }); } async processForm(event) { event.preventDefault(); const userclient = this.state.client.userclient; const clientname = this.state.client.clientname; const clientbusinessname = this.state.client.clientbusinessname; const password = this.state.client.password; const confirmPassword = this.state.client.confirmPassword; const formData = { userclient, clientname, clientbusinessname, password, confirmPassword }; axios.post('/signup', formData, { headers: {'Accept': 'application/json'} }) .then((response) => { this.setState({ errors: {} }); <Redirect to="/"/> // Here, nothings happens }).catch((error) => { const errors = error.response.data.errors ? error.response.data.errors : {}; errors.summary = error.response.data.message; this.setState({ errors }); }); } render() { return ( <div className={styles.section}> <div className={styles.container}> <img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} /> <SignUpForm onSubmit={this.processForm} onChange={this.changeClient} errors={this.state.errors} client={this.state.client} /> <Footer /> </div> </div> ); } } export default SignUpPage;
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Debe usar setState para establecer una propiedad que representará <Redirect> dentro de su método render() .

P.ej

 class MyComponent extends React.Component { state = { redirect: false } handleSubmit () { axios.post(/**/) .then(() => this.setState({ redirect: true })); } render () { const { redirect } = this.state; if (redirect) { return <Redirect to='/somewhere'/>; } return <RenderYourForm/>; }

También puede ver un ejemplo en la documentación oficial: https://reacttraining.com/react-router/web/example/auth-workflow


Dicho esto, le sugiero que coloque la llamada API dentro de un servicio o algo así. Entonces podría usar el objeto de history para enrutar programáticamente. Así es como funciona la integración con redux .

Pero supongo que tienes tus razones para hacerlo de esta manera.

over 4 years ago · Santiago Trujillo Report

0

Aquí un pequeño ejemplo como respuesta al título ya que todos los ejemplos mencionados son complicados en mi opinión al igual que el oficial.

Debe saber cómo transpilar es2015 y cómo hacer que su servidor pueda manejar la redirección. Aquí hay un fragmento de express. Puede encontrar más información relacionada con esto aquí .

Asegúrese de poner esto debajo de todas las demás rutas.

 const app = express(); app.use(express.static('distApp')); /** * Enable routing with React. */ app.get('*', (req, res) => { res.sendFile(path.resolve('distApp', 'index.html')); });

Este es el archivo .jsx. Observe cómo el camino más largo viene primero y se vuelve más general. Para las rutas más generales, utilice el atributo exacto.

 // Relative imports import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom'; // Absolute imports import YourReactComp from './YourReactComp.jsx'; const root = document.getElementById('root'); const MainPage= () => ( <div>Main Page</div> ); const EditPage= () => ( <div>Edit Page</div> ); const NoMatch = () => ( <p>No Match</p> ); const RoutedApp = () => ( <BrowserRouter > <Switch> <Route path="/items/:id" component={EditPage} /> <Route exact path="/items" component={MainPage} /> <Route path="/yourReactComp" component={YourReactComp} /> <Route exact path="/" render={() => (<Redirect to="/items" />)} /> <Route path="*" component={NoMatch} /> </Switch> </BrowserRouter> ); ReactDOM.render(<RoutedApp />, root);
over 4 years ago · Santiago Trujillo Report

0

React Router v5 ahora te permite simplemente redirigir usando history.push() gracias al gancho useHistory() :

 import { useHistory } from "react-router-dom" function HomeButton() { let history = useHistory() function handleClick() { history.push("/home") } return ( <button type="button" onClick={handleClick}> Go home </button> ) }
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!