我正在学习useParamsReact 中的 hook。我有一个这样的 URL,需要从中提取字母 9。
useParams
http://localhost:3010/9/solution
我该怎么办?
要使用钩子从 React 组件中的 URL 中提取参数useParams,请按照
react-router-dom
npm install react-router-dom
或者
yarn add react-router-dom
App.js
``` import React from ‘react’; import {
BrowserRouter as Router, Route, Routes, } } fro from ‘react-router-dom’;
im import Solution from ‘./Solution’;
functi function App() {
r
return (
<<Router> <Routes> <Route path="/:id/solution" element={<Solution />} /> </Routes> </Router> );
}
);
expor
ex
); < <Route path="/:id/solution" element={<So <
export default App; ```
Solution
``` jsx复制代码import React from ‘react’;
impor
im import { useParams } from ‘react-router-dom’;
function Solution() { const { id } = useParams();
return ( <div> <h1>Solution Component</h1> <p>The extracted ID is: {id}</p> </div> );
export default Solution; ```
以下是具体情况:
App
/:id/solution
:id
id
现在,当您导航到 时http://localhost:3010/9/solution,Solution组件将提取参数(在本例中id为)并显示它。9
9