[英]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.我想要一个简单的按钮,单击该按钮时会将用户重定向到我的 Index.tsx 文件中定义的路由。
When the button is clicked, the url bar is correctly changed to "/dashboard", however my component (just an h1) does not appear.单击按钮时,url 栏正确更改为“/dashboard”,但是我的组件(只是一个 h1)没有出现。 If I reload chrome at that point it will appear.
如果我在那时重新加载 chrome,它将出现。
Here's my code (Index.tsx):这是我的代码(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).这是我登录表单的开始(上面的第一条路线,App,呈现它)。 (Login.tsx):
(登录.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尝试从
react-router-dom
导入Router
- 其余的似乎是正确的
import { Route, Router, Switch } from "react-router-dom";
react-router
is mostly for internal usage - you only interact with react-router-dom
react-router
主要用于内部使用 - 您只与react-router-dom
交互
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.