Redirect after completing an action with react-router-dom V5.+

*爱你&永不变心* 提交于 2021-01-29 05:11:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!