记录一次react-router@5.x路由跳转后页面不刷新问题

643 阅读1分钟

在使用react-router是遇到一个问题, 示例代码如下,在线demo:

import { createBrowserHistory } from "history";
import { Router, Route, Switch } from "react-router";

const history = createBrowserHistory();

const Page1 = (props) => {
  return <div key={props.location.key}>Page1</div>;
};

const Page2 = (props) => {
  return <div key={props.location.key}>Page2</div>;
};

export default function App() {
  return (
    <div className="App">
      <ul>
        <li>
          <span
            onClick={() => {
              history.push("/path1");
            }}
          >
            page1
          </span>
        </li>
        <li>
          <span
            onClick={() => {
              history.push("/path2");
            }}
          >
            page2
          </span>
        </li>
      </ul>
      <Router history={history}>
        <Switch>
          <Route path="/path1" component={Page1} exact />
          <Route path="/path2" component={Page2} exact />
        </Switch>
      </Router>
    </div>
  );
}

点击菜单路由跳转,但是对应的页面并未渲染出来。

原因

history库版本不对,我们的react-router大版本为5,history的大版本也为5; history版本改为4.x,页面正常渲染。

我在history的官网上找到如下描述:

20210727111845

意思是说,react-router@6.x使用的是history@5.xreact-router@4.xreact-router@5.x使用的是history@4.x