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.6K
Views
usando el historial con react-router-dom v6

Uso react-router-dom version 6 y cuando uso this.props.history.push('/UserDashboard') no funciona. lo cambié a

 const history = createBrowserHistory(); history.push('/UserDashboard')

pero todavía tengo el problema de que cuando me gustaría redirigir a /UserDashboard solo cambia el enlace y la página sigue siendo la primera.

¿¿alguna ayuda??**

 handleSubmit(event){ event.preventDefault(); const history = createBrowserHistory(); axios({ method: "POST", url:"http://localhost:3001/users/login", data: this.state }).then((response)=>{ console.log(response.data.user.admin) if (response.data.success === true && response.data.user.admin === false){ const history = createBrowserHistory(); history.push({ pathname:"/users", state:{ Key : response.data.user } }); }else if(response.statusCode === 401 ){ alert("Invalid username or password"); window.location.reload(false); } }) }

mi archivo route.js:

 import React from 'react'; import { Navigate } from 'react-router-dom'; import DashboardLayout from './Pages/DashboardLayout'; import AccountView from './Pages/views/account/AccountView'; import CustomerListView from './Pages/views/customer/CustomerListView'; import DashboardView from './Pages/views/reports/DashboardView'; import ProductListView from './Pages/views/product/ProductListView'; import SettingsView from './Pages/views/settings/SettingsView'; import Home from './Pages/home'; import About from './Pages/About'; import Partners from './Pages/Partners'; import Services from './Pages/services'; import Login from './Pages/Login'; import RD from './Pages/RD'; import ContactUs from './Pages/contactus'; import Apply from './Pages/apply'; import PartnerShip from './Pages/partnership'; import News from './Pages/News'; const routes = [ { path: 'users', element: <DashboardLayout />, children: [ { path: 'account', element: <AccountView /> }, { path: 'customers', element: <CustomerListView /> }, { path: 'dashboard', element: <DashboardView /> }, { path: 'products', element: <ProductListView /> }, { path: 'settings', element: <SettingsView /> } ] }, { path: '/', element: <Home />, }, { path: 'about', element: <About /> }, {path: 'partners', element: <Partners />, }, { path: 'services', element: <Services />, }, { path: 'contactus', element: <ContactUs />, }, { path: 'login', element: <Login />, },{ path: 'RD', element: <RD />, }, { path: 'apply', element: <Apply />, }, { path: 'partnership', element: <PartnerShip />, }, { path: 'News', element: <News />, } ]; export default routes;
over 4 years ago · Santiago Trujillo
6 answers
Answer question

0

En react-router-dom v6, debe usar useNavigate en lugar de useHistory.

Ver ejemplo de https://reacttraining.com/blog/react-router-v6-pre/

 import React from 'react'; import { useNavigate } from 'react-router-dom'; function App() { let navigate = useNavigate(); let [error, setError] = React.useState(null); async function handleSubmit(event) { event.preventDefault(); let result = await submitForm(event.target); if (result.error) { setError(result.error); } else { navigate('success'); } } return ( <form onSubmit={handleSubmit}> // ... </form> ); }
over 4 years ago · Santiago Trujillo Report

0

Basado en el código fuente de react-router-dom, puede hacer algo como esto:

 import { Router } from 'react-router-dom'; const CustomRouter = ({ basename, children, history, }) => { const [state, setState] = React.useState({ action: history.action, location: history.location, }); React.useLayoutEffect(() => history.listen(setState), [history]); return ( <Router basename={basename} children={children} location={state.location} navigationType={state.action} navigator={history} /> ); };

Entonces haz que tu historia venga de fuera:

 import { createBrowserHistory } from 'history'; const history = createBrowserHistory(); <CustomRouter history={history}> ... </CustomRouter>
over 4 years ago · Santiago Trujillo Report

0

Otra solución, si todavía usa componentes de clase en reaccionar v6+, es inyectar el nuevo objeto de navegación como historial. Esto soluciona el molesto problema de no poder usar la función de navigate() dentro de un componente de clase, aunque debería intentar alejarse de los componentes de clase en el futuro. Me encontré en esta situación con una gran base de código, como estoy seguro de que otros todavía lo están.

 import React, { Component } from "react"; import { useNavigate } from "react-router-dom"; class MyClass extends Component { handleClick(e) => { this.props.history('place-to-route'); } } export default (props) => ( <MyClass history={useNavigate()} /> );
over 4 years ago · Santiago Trujillo Report

0

Todos sabemos que ya no hay { useHistory } en react-router-dom v6. Hay una mejor manera de hacer un trabajo de useHistory.

Primera importación useNavegar...

import { useNavigate } from 'react-router-dom';

entonces solo haz esto después de importar

 function Test() { const history = useNavigate(); function handleSubmit(e) { e.preventDefault(); history('/home'); } return ( <form onSubmit={handleSubmit}> <button>Subimt</button> </form> ) }
over 4 years ago · Santiago Trujillo Report

0

Puede utilizar la solución descrita en

[https://reactnavigation.org/docs/use-navigation/][1]

 class MyBackButton extends React.Component { render() { // Get it from props const { navigation } = this.props; } } // Wrap and export export default function(props) { const navigation = useNavigation(); return <MyBackButton {...props} navigation={navigation} />; }

over 4 years ago · Santiago Trujillo Report

0

Reactjs v6 viene con useNavigate en lugar de useHistory.

=> en primer lugar, debe importarlo así: import {useNavigate} from 'react-router-dom'.

=> entonces solo puede usarlo bajo un componente funcional de reacción como este:

const navegar = useNavegar() ;

=> Y luego en qué ruta desea navegar, simplemente coloque el nombre de la ruta de esta manera:

navegar("/sobre");

ejemplo: si desea navegar a la página acerca de después de hacer clic en un botón. Entonces debe poner

navegar("/sobre") bajo este evento onClick:

<button onClick = {()=>navegar("/acerca de")}>ir a la página acerca de

Gracias.

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!