路由器不适用于 Link (React Router Dom 6)

Router does not work with Link (React Router Dom 6)

所以我在一个新的原始 CRA 5 (typescript) 应用程序上测试了这个。在 App.tsx 中,我只是将其内容替换为:

import { Router, Routes, Route, Link } from "react-router-dom";
import "./App.css";

interface IProps {
  appHistory: any;
}

function App(props: IProps) {
  const { appHistory } = props;

  return (
    <div className="App">
      <Router location={appHistory.location} navigator={appHistory}>
        <ul>
          <li>
            <Link to="/">
              <strong>Home</strong>
            </Link>
          </li>
          <li>
            <Link to="/about">
              <strong>About</strong>
            </Link>
          </li>
          <li>
            <Link to="/pricing">
              <strong>Pricing</strong>
            </Link>
          </li>
        </ul>

        <Routes>
          <Route path="/" element={<div>Home Page</div>}></Route>
          <Route path="/about" element={<div>About Page</div>}></Route>
          <Route path="/pricing" element={<div>Pricing Page</div>}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

index.tsx到这个:

import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserHistory } from "history";
import "./index.css";
import App from "./App";

const appHistory = createBrowserHistory();
const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(
  <React.StrictMode>
    <App appHistory={appHistory} />
  </React.StrictMode>
);

这似乎不起作用。路由不起作用。无论您单击什么,它都会停留在主页上。没有控制台错误日志。

我想明确使用 Router 组件来满足应用程序设计要求。 (试用微前端架构)。

有人知道我在这里错过了什么吗?

感谢任何帮助! 提前致谢!

库版本:

"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"typescript": "^4.6.3",
"history": "^5.3.0"

备注

const appHistory = createBrowserHistory() 移出组件。你想要一个稳定的历史参考。

您还需要实现一些历史状态。使用 BrowserRouter source 代码作为 high-level 路由器如何实例化其历史上下文的示例。

示例:

const history = createBrowserHistory();

function App() {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Router
        location={state.location}
        navigationType={state.action}
        navigator={history}
      >
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/pricing">Pricing</Link>
          </li>
        </ul>
        <Routes>
          <Route path="/" element={<h1>Home</h1>} />
          <Route path="/about" element={<h1>About</h1>} />
          <Route path="/pricing" element={<h1>Pricing</h1>} />
        </Routes>
      </Router>
    </div>
  );
}