React项目点击当前页组件跳转新页面时如何加载对应组件数据
实现方案说明
这个需求完全可以实现,以下是基于React生态的常规实现步骤,默认你已经在项目中接入了react-router-dom做路由管理:
方案1:动态路由传参(推荐,支持页面刷新、链接分享)
这是最常用的实现方式,适配你从外部API拿数据的场景:
- 第一步:配置详情页动态路由,在路由规则中新增一条配置:
path: '/recipe/:recipeId',对应组件绑定为你的餐食详情页组件 - 第二步:给首页的缩略图组件绑定跳转逻辑,跳转时携带当前点击食谱的唯一ID:如果用Link组件写法为
<Link to={/recipe/${currentRecipe.id}}>{/* 缩略图内容 */}</Link>,如果用useNavigate写法为navigate(/recipe/${currentRecipe.id}) - 第三步:在详情页通过
useParams钩子拿到路由中的食谱ID,拿着该ID请求外部API的食谱详情接口,获取到完整的份量、食材、制作步骤等数据后,直接渲染对应内容即可
该方案优势是详情页刷新、分享链接给其他用户打开后,都能正常展示对应食谱内容。
方案2:路由State传参(适合无需分享、首页已拿到全量数据的场景)
如果你的首页列表接口已经返回了所有食谱的完整信息,不需要二次调用详情接口,可以用该方案:
- 第一步:跳转时把完整的食谱对象存入路由State:如果用Link组件写法为
<Link to="/recipe" state={{ recipeInfo: currentRecipe }}>{/* 缩略图内容 */}</Link>,如果用useNavigate写法为navigate('/recipe', { state: { recipeInfo: currentRecipe } }) - 第二步:在详情页通过
useLocation钩子拿到State数据:const { state } = useLocation(); const recipeInfo = state?.recipeInfo,直接取对应字段渲染即可
注意该方案下刷新详情页会丢失State数据,如果需要支持刷新请选择方案1。
基础代码示例(基于react-router-dom v6版本)
首页缩略图组件
import { Link } from 'react-router-dom' function HomePage() { // recipeList为你从外部API拿到的食谱列表数据 const recipeList = [] return ( <div className="recipe-list"> {recipeList.map(item => ( <Link key={item.id} to={`/recipe/${item.id}`} className="recipe-card"> <img src={item.image} alt={item.title} /> <h3>{item.title}</h3> </Link> ))} </div> ) }
餐食详情页组件
import { useState, useEffect } from 'react' import { useParams } from 'react-router-dom' function RecipeDetail() { const { recipeId } = useParams() const [detail, setDetail] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { setLoading(true) // 替换为你实际使用的外部API详情接口地址 fetch(`https://your-api-domain/recipe/${recipeId}`) .then(res => res.json()) .then(data => { setDetail(data) setLoading(false) }) }, [recipeId]) if (loading) return <div>加载中...</div> return ( <div className="detail-page"> <h1>{detail.title}</h1> <img src={detail.image} alt={detail.title} /> <p>份量:{detail.servings} 人份</p> <h2>食材清单</h2> <ul> {detail.ingredients.map((ing, idx) => <li key={idx}>{ing}</li>)} </ul> <h2>制作步骤</h2> <div className="steps"> {detail.steps.map((step, idx) => <p key={idx}>{idx+1}. {step}</p>)} </div> </div> ) }
内容的提问来源于stack exchange,提问作者rebel-sloth
相关产品推荐
相关产品推荐

