使用 react-router-dom V5.+ 完成操作后重定向
Redirect after completing an action with react-router-dom V5.+
我在使用 react-router-dom 在屏幕之间导航时遇到问题。我想做的是在完成一个动作后我想导航到其他屏幕。很抱歉这个菜鸟问题,但这是我第一次使用 React。
尝试使用这些命令
this.props.history.push("/Home")// use this for class component
props.history.push("/Home")// functional component (and pass props to the component)
示例:
function LoginComponent(props) {
const handleClick=()=> {
props.history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
并确保您在 app.js
中编写了路由
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./components/Home";
<Router>
<Route path="/home" component={Home} />
</Router>
如果您正在使用挂钩,请使用 react-router doms useHistory 挂钩 https://reactrouter.com/web/api/Hooks
例如:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
我在使用 react-router-dom 在屏幕之间导航时遇到问题。我想做的是在完成一个动作后我想导航到其他屏幕。很抱歉这个菜鸟问题,但这是我第一次使用 React。
尝试使用这些命令
this.props.history.push("/Home")// use this for class component
props.history.push("/Home")// functional component (and pass props to the component)
示例:
function LoginComponent(props) {
const handleClick=()=> {
props.history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
并确保您在 app.js
中编写了路由import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./components/Home";
<Router>
<Route path="/home" component={Home} />
</Router>
如果您正在使用挂钩,请使用 react-router doms useHistory 挂钩 https://reactrouter.com/web/api/Hooks
例如:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}