【问题标题】:useParams() is an empty object in react-router-dom v6.8useParams() 在 react-router-dom v6.8 中是一个空对象
【发布时间】:2023-02-01 14:44:33
【问题描述】:

我只是想在 React 中使用 react-router-dom v 6.8 从动态路由 ("/articles/:articleId") 检索参数

"react-router-dom": "^6.8.0",    
"@types/react-router-dom": "^5.3.3",

我试图关注the Docs,但我一定在这里遗漏了一些东西。

应用程序.tsx

function App() {
  return (
    <Router>
      <Routes>
        <Route path={"/articles/:articleId"} element={Article()}/>
        <Route path={"/articles"} element={Articles()}/>
        <Route path={"/404"} element={NotFoundPage()}/>
        <Route path={"/"} element={HomePage()}/>
        <Route path={"*"} element={NotFoundPage()}/>
      </Routes>
    </Router>
  );
}

文章.tsx

import { useParams } from "react-router-dom";
import { useEffect } from "react";

const Article = () => {
  const { articleId } = useParams()
  const params = useParams()

  useEffect(() => {
    console.log('even inside useEffect', params);
  }, [])
    
  console.log("Article  ", useParams(), articleId)

  return (
    <div>ID: {articleId}</div>
  )
}

export default Article

输出

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

    几个问题:

    1. 您直接调用 React 函数而不是将它们渲染为 JSX。这些组件不会作为正常 React 组件生命周期的一部分被调用,因此不会填充参数。
    2. react-router-dom@6 完全用 Typescript 编写,因此不需要任何外部类型,尤其是来自 react-router-dom@5 的类型,这对于 RRDv6 来说是非常不正确的。

      Route 组件的 element 属性采用 React.ReactNode,又名 JSX,值。

      function App() {
        return (
          <Router>
            <Routes>
              <Route path="/articles/:articleId" element={<Article />} />
              <Route path="/articles" element={<Articles />} />
              <Route path="/404" element={<NotFoundPage />} />
              <Route path="/" element={<HomePage />} />
              <Route path="*" element={<NotFoundPage />} />
            </Routes>
          </Router>
        );
      }
      

      卸载不必要的依赖。

      npm uninstall --save @types/react-router-dom
      

    【讨论】:

    • 我很惊讶我的 IDE 没有指出这一点。感谢您的快速回答?。有效。
    猜你喜欢
    • 2020-07-13
    • 2021-05-10
    • 2023-02-06
    • 2020-02-21
    • 2022-12-10
    • 2022-01-12
    • 2021-05-06
    • 2022-06-16
    • 2022-12-22
    相关资源
    最近更新 更多