【问题标题】:useParams() unable to fetch path dynamically react-router v6useParams() 无法动态获取路径 react-router v6
【发布时间】:2021-11-22 03:00:27
【问题描述】:
import { Route, Routes, Navigate } from "react-router-dom";
import AllQuotes from './pages/AllQuotes';
import QuoteDetail from './pages/QuoteDetail';

function App() {
  return (
    <div>
      <Routes>
        <Route path='/' element={<Navigate to='/quotes' />} />
        <Route path='/quotes' element={<AllQuotes />} />
        <Route path='/quotes/*' element={<QuoteDetail />} />
        <Route path='/quotes/:quoteId' element={<QuoteDetail />} />
      </Routes>
    </div>
  );
}

export default App;

这是我的报价详情代码

import { Fragment } from "react";
import { useParams } from "react-router";
import { Routes, Route } from "react-router-dom";
import Comments from "../components/comments/Comments";

const QuoteDetail = () => {
  const params = useParams();

  console.log(params.quoteId);

  return (
    <Fragment>
      <h1>Quote Detail Page</h1>
      <p>{params.quoteId}</p>
      <Routes>
        <Route 
          path={`${params.quoteId}/comments`}
          element={<p>Hello</p>}
        />
      </Routes>
    </Fragment>
  );
};

export default QuoteDetail;

当我使用动态路径值时,我的代码无法呈现 QuoteDetail 代码块中存在的嵌套路由组件的元素

【问题讨论】:

    标签: reactjs react-router frontend react-router-dom multipage


    【解决方案1】:

    如果QuoteDetail 正在呈现子路由,则在“quoteId”路由的末尾指定* 通配符以允许进一步/更深入的匹配。

    function App() {
      return (
        <div>
          <Routes>
            <Route path='/' element={<Navigate to='/quotes' />} />
            <Route path='/quotes' element={<AllQuotes />} />
            <Route path='/quotes/:quoteId/*' element={<QuoteDetail />} />
          </Routes>
        </div>
      );
    }
    

    您也可以使用来自QuoteDetail 的相对匹配/链接,实际上不需要知道当前的quoteId 来创建链接并匹配更多的子路由。您可以只指定当前位置的相对路径。以"/" 开头的路径是绝对的,没有的是相对的。

    const QuoteDetail = () => {
      const params = useParams();
    
      return (
        <Fragment>
          <h1>Quote Detail Page</h1>
          <p>{params.quoteId}</p>
          <Routes>
            <Route 
              path="comments"
              element={<p>Hello</p>}
            />
          </Routes>
        </Fragment>
      );
    };
    

    【讨论】:

    • 如何在QuoteDetail页面上动态呈现quoteId?
    • @HIARTHVYAS 使用const params = useParams()const { quoteId } = useParams() 应该足够了。当路由改变并且 url/path 不同时,它应该重新渲染路由,从而重新渲染组件。您应该会看到任何新的 quoteId 匹配参数值。
    • 我尝试使用{ quoteId } = useParams() 并在路由组件中动态呈现路径,但实际上并没有工作,因为您可以看到我的 QuoteDetails 代码。
    • @HIARTHVYAS 你看到它在我链接的codeandbox中是如何工作的吗?如果它仍然不适合您,您可以尝试创建自己的代码框来重现我们可以实时检查和调试的问题吗?
    • 您的代码正在运行,先生,但我不知道我的代码有什么问题,为什么它在 console.log() 中显示 params.quoteId undefined
    猜你喜欢
    • 2021-05-21
    • 2022-08-14
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2022-07-12
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多