【问题标题】:Redirect after completing an action with react-router-dom V5.+使用 react-router-dom V5.+ 完成操作后重定向
【发布时间】:2020-09-15 19:19:47
【问题描述】:

我在使用 react-router-dom 在屏幕之间导航时遇到问题。我想做的是在完成一个动作后我想导航到其他屏幕。很抱歉这个菜鸟问题,但这是我第一次使用 react。

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: reactjs web-applications screen router


【解决方案1】:

如果你使用钩子,请使用 react-router dom useHistory hook 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>
  );
}

【讨论】:

    【解决方案2】:

    尝试使用这些命令

    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>
    

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 2019-07-30
      • 2022-08-07
      • 2022-12-31
      • 1970-01-01
      • 2018-05-21
      • 2020-08-10
      • 2021-07-27
      • 1970-01-01
      相关资源
      最近更新 更多