react函数式组件(非路由组件)实现路由跳转

个人理解:

 <Route exact path="/Home" component={Home}/>
 1.路由组件:只有包裹在Route组件里的才能使用`this.props.location`,
 2.非路由组件:假如有个需求,是面包屑或者导航组件里需要拿到`this.props.location`(导航组件或者面包屑一般不会包裹在`Route`里吧),那么直接这么写显然就不行了。
 这个时候`withRouter`修饰一下,就可以这么写了。

useHistory

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>
  );
}

文档在这里

.

原文地址:https://www.cnblogs.com/jianxian/p/12585340.html