React Router中<Link>组件通过state传参出现undefined问题求助
问题:React Router Link传递state时出现undefined错误
从API读取数据并存储在useState声明的projekter变量中,映射该变量时所有值均正常显示,但尝试通过<Link>组件的state属性将值传递到SingularProjekt组件时,出现undefined或“无法读取undefined的‘state’属性”错误。
相关代码
获取数据的代码
import mistoContentful from "../Helpers/mistoContentful"; const ProjektMain = () => { const [projekter, setProjekter] = useState([]); const { getContentData } = mistoContentful(); useEffect(() => { getContentData().then((response) => setProjekter(response)); }, [getContentData]); return ( <div className="projektMain">
映射并传递数据的代码
<div className=" gridContainer grid gap-6 grid-flow-row justify-center mt-60 mb-40 md:grid-cols-3 md:mx-11 xl:mx-16 2xl:mx-auto 2xl:max-w-max 2xl:gap-14 "> {projekter.map((projektInfo) => ( <div key={projektInfo.id} className=" gridItem box-border aspect-square 2xl:max-w-[30rem] relative" > <Link key={projektInfo.id} to={{ pathname: "/SingularProjekt", state: { info: projektInfo }, }} > <img className=" object-cover bg-cover h-full hover:border-[#D4B572] hover:border-4" src={projektInfo.projectCover} /> <div className="absolute text-center opacity-90 bottom-0 bg-slate-500 w-[100%] h-[1.5rem] 2xl:h-8"> <p className=" font-oswald opacity-100 2xl:text-xl"> {projektInfo.projectTitle} {/* {console.log(projektInfo)} */} </p> </div> </Link> </div>
接收数据的SingularProjekt组件代码
const SingularProjekt = (props) => { const { projektInfo } = props.location.state; return ( <div className=" bg-[#666E70] h-full "> <Nav /> <div className="flex relative md:max-w-[95%] lg:pt-10 2xl:max-w-[100rem] 2xl:mx-auto"> <img className="md:pl-5" src={tapas} /> <div className=" divShadow1 flex items-center justify-center bg-[#505E57] aspect-square absolute bottom-[-11%] right-3 text-center "> <p className=" font-oswald text-base max-w-[80%] md:text-2xl lg:text-3xl xl:text-4xl 2xl:text-5xl"> Ho`s Tapas{console.log(projektInfo)} </p> </div>
解决建议
修正键名匹配问题
传递state时用的是info: projektInfo,但接收时解构的是projektInfo,两者不匹配。要么修改传递代码为state: { projektInfo }(ES6简写),要么修改接收代码为const { info } = props.location.state;。添加边界情况处理
直接访问props.location.state会因为页面刷新、直接输入URL跳转等场景导致state丢失,必须先判断是否存在:const SingularProjekt = (props) => { if (!props.location?.state) { return <div>数据加载失败,请返回项目列表页</div>; } const { info } = props.location.state; // 或对应匹配的键名 // 后续渲染逻辑 }确认React Router版本用法
如果使用React Router v6,必须用useLocation钩子接收state,不能通过props获取:import { useLocation } from 'react-router-dom'; const SingularProjekt = () => { const location = useLocation(); if (!location?.state) { return <div>数据加载失败,请返回项目列表页</div>; } const { info } = location.state; // 后续渲染逻辑 }确保数据可序列化
React Router传递的state必须是可JSON序列化的,若projektInfo包含函数、Symbol等非序列化值,会导致state丢失。建议只传递需要的字段:<Link to={{ pathname: "/SingularProjekt", state: { info: { id: projektInfo.id, projectTitle: projektInfo.projectTitle, projectCover: projektInfo.projectCover } }, }} >
内容的提问来源于stack exchange,提问作者Ephraim Valladares Cordova
相关产品推荐
相关产品推荐

