问题
I'm having trouble with navigating between screen with react-router-dom. What I'm trying to do is that after completing an action I want to navigate to other screen. Sorry for the noob question but it's my first time working with react.
回答1:
if you are using hooks, use react-router doms useHistory hook https://reactrouter.com/web/api/Hooks
for example:
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>
);
}
回答2:
try using these commands
this.props.history.push("/Home")// use this for class component
props.history.push("/Home")// functional component (and pass props to the component)
Example:
function LoginComponent(props) {
const handleClick=()=> {
props.history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
and make sure you wrote Routes in the app.js
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./components/Home";
<Router>
<Route path="/home" component={Home} />
</Router>
来源:https://stackoverflow.com/questions/63908529/redirect-after-completing-an-action-with-react-router-dom-v5