简体   繁体   中英

React Router useHistory. History.push changes url but does not load component

I want to have a simple button that when clicked redirects a user to a route defined in my Index.tsx file.

When the button is clicked, the url bar is correctly changed to "/dashboard", however my component (just an h1) does not appear. If I reload chrome at that point it will appear.

Here's my code (Index.tsx):

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Route, Switch } from "react-router-dom";
import { Router } from "react-router";
import { createBrowserHistory } from "history";
import Dashboard from "./components/Dashboard";

const appHistory = createBrowserHistory();

ReactDOM.render(
  <React.StrictMode>
    <Router history={appHistory}>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/dashboard" component={Dashboard} />
      </Switch>
    </Router>
  </React.StrictMode>,
   document.getElementById("root")
  );

Here's my start of a Login form (the first route above, App, renders it). (Login.tsx):

 import React, { useState } from "react";
 import {Button} from "@material-ui/core";
 import { useHistory} from "react-router-dom";

 export const Login: React.FC = (props) => {
     const classes = useStyles();
     let history = useHistory();

     const [email, setEmail] = useState<string>("");
     const [password, setPassword] = useState<string>("");

     const validateForm = (): boolean => {
        return true;
     };

     const handleLoginClick = (
       event: React.MouseEvent<HTMLButtonElement, MouseEvent>
      ) => {
         history.push("/dashboard");
     };

     return (
        <form>
         <div>
           <Button
            onClick={handleLoginClick}
            color="inherit"
            type="button"
           >
            Login
           </Button>
         </div>
        </form>
       );
 };

 export default Login;

Replace this line

import { Router } from "react-router"

with

import {BrowserRouter as Router } from "react-router-dom";

Try importing the Router from react-router-dom - the rest seems correct

import { Route, Router, Switch } from "react-router-dom";

react-router is mostly for internal usage - you only interact with react-router-dom

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