【问题标题】:React: Pass parameters using React-Router v6React:使用 React-Router v6 传递参数
【发布时间】:2022-07-21 16:21:50
【问题描述】:

声明了我所有路由的 App.js:

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/">
          <Route index element={<Homepage />} />
          <Route path="settings" element={<Settings />} />
          <Route path="report/:runId" element={<TestReport />} />
          <Route path="report/:runId/:specFileName" element={<SpecFile />} />
        </Route>
      </Routes>
    </div>
  )
}

这里我有链接到(在我目前的情况下)/report/2/Login,我想在其中传递一些参数:

   <TableCell>
      <Link
         to={`/report/${this.props.runId}/${specFile.name}`}
         state={{ testcases: this.props.testcases }}
      >
         {specFile.name}
      </Link>
   </TableCell>

在这里我想访问我的参数:

import { useLocation } from "react-router-dom";

export default function SpecFile() {
   const location = useLocation();
   const { from } = location.specFile.name;
   console.log(from); // Should print "Login" instead gives Error Message: Cannot read properties of undefined (reading 'name')
}

【问题讨论】:

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


    【解决方案1】:

    react-router-6 中有一个钩子。

    import { useSearchParams } from 'react-router-dom';
    

    然后像这样使用它:

    const [searchParams] = useSearchParams();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多