React中如何获取跨页面传递的ID?跳转详情页失败求助
问题解决:作曲家详情页无法加载的问题
核心错误点
- 详情页ID获取逻辑错误:你试图从
backUrl参数取ID,但跳转时传递的是id参数,且路由已配置动态/:id参数,应该通过路由参数获取ID。 - 请求URL错误:
http://localhost:3000/api/composers/id里的id是固定字符串,没有替换为实际作曲家ID。 - useEffect依赖项错误:依赖了未定义的
_id,导致逻辑触发异常。 - 跳转链接冗余:已经通过路由动态参数传递ID,无需额外添加search参数。
修正步骤
1. 简化作曲家页面的跳转链接
去掉冗余的search参数,直接通过路由动态参数传递ID:
{albums.map(album => ( <Link to={`/api/composers/${album._id}`} key={album._id} style={{ textDecoration: "none", color: "black" }} > <Card className="albums-card"> <img src={album.image} alt={`${album.name} thumbnail`} /> <h5>{album.name}</h5> <h6>{album.nationality}</h6> </Card> </Link> ))}
2. 修正详情页的ID获取与请求逻辑
使用useParams获取路由动态参数,修正请求URL并添加错误捕获:
import { useParams } from 'react-router-dom'; // ...其他必要导入 // 从路由中获取ID参数 const { id } = useParams(); useEffect(() => { setIsLoading(true); const fetchData = async () => { try { const result = await fetch( `http://localhost:3000/api/composers/${id}` ); // 检查请求是否成功 if (!result.ok) throw new Error('请求失败'); const resultJson = await result.json(); setItems(resultJson); } catch (error) { console.error('加载数据失败:', error); // 可在此添加前端错误提示逻辑 } finally { setIsLoading(false); } }; // 仅当ID存在时发起请求 if (id) fetchData(); }, [id]); // 依赖项改为获取到的id
3. 验证路由配置
你的路由配置本身正确,只需确认ComposerMongodb组件就是对应详情页的组件(注意与代码中的Profile.js命名一致性):
<Routes> <Route path="/" element={<Home />} /> <Route path="/api/composers" element={<Composer />} /> <Route path="/api/composers/:id" element={<ComposerMongodb />} /> </Routes>
额外注意事项
- 确认后端API
/api/composers/:id可正常响应,返回合法JSON数据。 - 若前后端端口不同,需在后端配置CORS以避免跨域问题。
内容的提问来源于stack exchange,提问作者Lucas R.G
相关产品推荐
相关产品推荐

