我想要一个简单的按钮,单击该按钮会将用户重定向到我的Index.tsx文件中定义的路由。
单击按钮后,URL栏将正确更改为“ / dashboard”,但是我的组件(仅为h1)没有出现。如果我在那时重新加载chrome,它将出现。
这是我的代码(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")
);
这是我登录表单的开始(上面的第一条路线,App,呈现它)。 (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;
答案 0 :(得分:4)
替换此行
import { Router } from "react-router"
使用
import {BrowserRouter as Router } from "react-router-dom";
答案 1 :(得分:2)
尝试从Router
导入react-router-dom
-其余的似乎正确
import { Route, Router, Switch } from "react-router-dom";
react-router
主要供内部使用-您仅与react-router-dom
互动