React学习笔记5:URL 参数获取-useParams

组件中获取参数

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

function MyComponent() {
  const params = useParams<{ bookId: string }>();
  console.log("🚀 ~ params:", params);
  const bookId = params.bookId;

  // 现在你可以使用bookId变量了
}

路由设置

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/book/:bookId" component={MyComponent} />
        {/* 其他路由 */}
      </Switch>
    </Router>
  );
}

如果访问 /notes/CB_GbE3HQ3IPD5r6pj6oo6pz34q 将获取 CB_GbE3HQ3IPD5r6pj6oo6pz34q 作为 bookId

Comments

No comments yet. Why don’t you start the discussion?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注