简体   繁体   中英

history.push() updates url but does not render the component

When I try to navigate trougth my project history seems to not work to render other components.

import React from 'react';
import Login from './components/Login.jsx';
import Register from './components/Register';
import Apuntes from './components/Apuntes';
import history from './history/history';
import { Router } from 'react-router';
import { Route } from 'react-router-dom';

export function App() {
  return (
    <Router history={history}>
      <Route exact path='/login' component={Login} />
      <Route exact path='/register' component={Register} />
      <Route exact path='/apuntes' component={Apuntes} />
    </Router>
  );
}

Then in my login class I call the history.push('/apuntes') and it changes the url but does nothing more. The history.js is this:

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

I would like to know how to fix this and get it to show the component depending the url.

this will work :)

//import your components here 
import {BrowserRouter as Router,Route, Switch, useHistory } from "react-router-dom";
export function App() {
const history = useHistory();
if (true) { // any condition you need here
   history.push("/login");
return (
  <Switch>     
  <Router>
    <Route exact path='/login'><Login/></Route>
    <Route exact path='/register'><Register/></Route>
    <Route exact path='/apuntes'><Apuntes/></Route>
  </Router>
</Switch>
);
}

plus you can define a route as default by adding this route at the end of routes.

  <Route path="/">
    <YourDefaultComponent/>
  </Route> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM