面试题答案
一键面试- 设置动态路由:
- 在React Router配置中添加动态路由。假设使用
react - router - dom
库,在路由配置文件(比如App.js
)中:
import { BrowserRouter as Router, Routes, Route } from'react - router - dom'; import UserPage from './UserPage'; function App() { return ( <Router> <Routes> <Route path="/user/:id" element={<UserPage />} /> <Route path="/home" element={<HomePage />} /> </Routes> </Router> ); } export default App;
- 在React Router配置中添加动态路由。假设使用
- 在
HomePage
中添加按钮并处理跳转:- 在
HomePage.js
中:
import { Link } from'react - router - dom'; function HomePage() { const handleClick = () => { // 假设要传递的查询参数 const queryParams = { name: 'John', age: 30 }; const queryString = new URLSearchParams(queryParams).toString(); const userId = 1; // 这里假设用户ID,实际可能从数据中获取 return <Link to={`/user/${userId}?${queryString}`}>跳转到用户详情</Link>; }; return ( <div> <h1>Home Page</h1> {handleClick()} </div> ); } export default HomePage;
- 在
- 在
UserPage
中获取参数并展示用户信息:- 在
UserPage.js
中:
import { useParams, useSearchParams } from'react - router - dom'; function UserPage() { const { id } = useParams(); const [searchParams] = useSearchParams(); const name = searchParams.get('name'); const age = searchParams.get('age'); // 这里可以根据id从API获取用户详细信息,假设模拟数据 const userInfo = { id, name, age }; return ( <div> <h1>User Detail</h1> <p>User ID: {userInfo.id}</p> <p>User Name: {userInfo.name}</p> <p>User Age: {userInfo.age}</p> </div> ); } export default UserPage;
- 在
具体步骤总结:
- 配置
react - router - dom
的动态路由。 - 在
HomePage
通过Link
组件并拼接包含查询参数的URL实现跳转。 - 在
UserPage
使用useParams
获取动态路由参数,使用useSearchParams
获取查询参数,并展示相关信息。