TypeError: Cannot read properties of undefined (reading 'location')

TypeError: Cannot read properties of undefined (reading 'location')

以下代码出现错误

history.location.pathname 正在抛出错误。(行号 - 3 和 6)

const LinkList = () => {
  const history = useHistory();
  const isNewPage = history.location.pathname.includes(
    'new'
  );
  const pageIndexParams = history.location.pathname.split(
    '/'
  );
  const page = parseInt(
    pageIndexParams[pageIndexParams.length - 1]
  );

我已经尝试了所有给出的解决方案,但仍然出现错误。

App.js

const App = () => {
  return (
    <div className="center w85">
      <Header />
      <div className="ph3 pv1 background-gray">
        <Routes>
          <Route exact path="/" render={() => <Redirect to="/new/1" />} />
          <Route exact path="/create" element={<CreateLink />} />
          <Route exact path="/login" element={<Login />} />
          <Route exact path="/search" element={<Search />} />
          <Route exact path="/home" element={<LinkList />} />
          <Route
          exact
          path="/new/:page"
          element={<LinkList />}
        />
        </Routes>
      </div>
    </div>
  );
};

依赖关系:

  "react-router": "^5.2.0",
  "react-router-dom": "^6.0.2",

react-router-dom 中不再有 useHistory 钩子,取而代之的是 useNavigate 钩子 returns 一个 navigate 函数而不是一个history 对象。

要获取当前位置,请使用 useLocation 挂钩。根据 v5 文档,您应该已经使用 location 对象而不是 history 对象,因为 history 对象是可变的。

const LinkList = () => {
  const { pathname } = useLocation();

  const isNewPage = pathname.includes('new');
  const pageIndexParams = pathname.split('/');
  const page = parseInt(
    pageIndexParams[pageIndexParams.length - 1]
  );

  ...

您也可以删除 react-router 依赖项,因为 react-router-dom 通常会重新导出所有 react-router 组件,或者至少也会将其升级到 v6,这样就没有版本冲突他们之间。

Redirect 在 RRDv6 中被 Navigate 组件取代,呈现重定向的新语法如下:

<Route path="/" element={<Navigate to="/new/1" replace />} />

此外,在 RRDv6 中,所有路由路径现在 always 完全匹配,exact 属性不是Route 组件 API.

您可以使用 useLocation hook 或 window.location.pathname 来访问路径名

useLocation returns 当前位置对象。 让位置=使用位置() 让路径=location.pathname