React Router报错:无法解构location.state的posterPath,如何正确传参?
问题解决:useLocation传递参数时location.state为null的报错
错误原因
你遇到的TypeError: Cannot destructure property 'posterPath' of 'location.state' as it is null,本质是**location.state可能为空**——比如用户直接在地址栏输入/details访问详情页,或者Card组件接收的posterPath为空,导致跳转时没有传递有效state。
修复方案
1. 给详情页组件加空值判断
修改MovieDetails组件,先判断location.state是否存在,再解构参数,同时处理空值情况:
const MovieDetails = () => { const location = useLocation(); // 用可选链+默认值避免解构null报错 const posterPath = location.state?.posterPath || ''; // 如果没有海报数据,显示占位提示 if (!posterPath) { return <div>暂无海报信息</div>; } return ( <div> <img className="w-44 hover:w-48 " alt="poster" src={`https://image.tmdb.org/t/p/w500${posterPath}`} /> </div> ); };
2. 确保Card组件传递有效参数
在Card组件中先校验posterPath是否存在,避免传递空state:
const Card = ({ posterPath }) => { // 如果没有海报路径,渲染占位图而非可跳转链接 if (!posterPath) { return ( <div className="pr-4 w-52 "> <img className="w-44 hover:w-48 " alt="占位海报" src="/your-placeholder-image.jpg" /> </div> ); } return ( <div className="pr-4 w-52 "> <Link to={{ pathname: "/details", state: { posterPath } }}> <img className="w-44 hover:w-48 " alt="poster" src={`https://image.tmdb.org/t/p/w500${posterPath}`} /> </Link> </div> ); };
额外提示
- 不要依赖
state作为唯一参数传递方式,如果需要支持直接访问详情页,可以考虑把posterPath放在URL参数中(比如/details?posterPath=xxx),用useSearchParams获取,兼容性更好。 - 模板字符串拼接URL比字符串相加更清晰,建议统一用
`xxx${variable}`的写法。
内容的提问来源于stack exchange,提问作者Raushan kumar
相关产品推荐
相关产品推荐

