React中如何通过资源URL与ID生成正确链接以获取单个对象
动态生成带ID的详情页链接问题解决
问题说明
我想通过对象ID从数据库获取单个对象,尝试用<a href="SinglePost:id">Read More......</a>生成链接,但鼠标悬停时显示的是singlepost:id,无法得到想要的singlepost/id=1格式链接。相关React代码如下:
import "./post.css"; import DateTime from "./DateTime"; import { useEffect, useState } from "react"; export default function Post() { const [posts, setPosts] = useState(null); useEffect(() => { fetch("http://localhost:8005/posts") .then((res) => { if (res.status !== 200) { throw Error("Post can not be found"); } else { return res.json(); } }) .then((data) => { setPosts(data); }) .catch((err) => { console.log(err.message); }); }, []); console.log(posts); return ( <div className="posts"> {posts && posts.map(({ id, image, posttitle, postdate, postdesc }) => { return ( <div key={id} className="post"> <img src={image} alt="imagedescription" className="postimage" /> <div className="postinfo"> <div className="postcats"> <span className="postcast">Music</span> <span className="postcast">Life</span> <span className="postcast">Music</span> </div> <span className="posttitle"> {id}. {posttitle} </span> <span className="postdate">{postdate}</span> </div> <p className="postdesc">{postdesc}</p> <span> {/* 原代码无法生成动态链接 */} <a href="SinglePost:id">Read More......</a> </span> </div> ); })} </div> ); }
解决方法
问题出在你用双引号包裹href值,这会把内容当作纯字符串,不会解析变量id。要生成动态链接,需要使用模板字符串(反引号`包裹)来拼接URL:
修改链接部分的代码:
<a href={`singlepost/id=${id}`}>Read More......</a>
原理说明
- 模板字符串允许在字符串中通过
${变量名}的方式插入动态值 - 这样每个帖子的链接都会根据自身的
id生成对应的singlepost/id=1、singlepost/id=2等格式
修改后的完整组件代码:
import "./post.css"; import DateTime from "./DateTime"; import { useEffect, useState } from "react"; export default function Post() { const [posts, setPosts] = useState(null); useEffect(() => { fetch("http://localhost:8005/posts") .then((res) => { if (res.status !== 200) { throw Error("Post can not be found"); } else { return res.json(); } }) .then((data) => { setPosts(data); }) .catch((err) => { console.log(err.message); }); }, []); console.log(posts); return ( <div className="posts"> {posts && posts.map(({ id, image, posttitle, postdate, postdesc }) => { return ( <div key={id} className="post"> <img src={image} alt="imagedescription" className="postimage" /> <div className="postinfo"> <div className="postcats"> <span className="postcast">Music</span> <span className="postcast">Life</span> <span className="postcast">Music</span> </div> <span className="posttitle"> {id}. {posttitle} </span> <span className="postdate">{postdate}</span> </div> <p className="postdesc">{postdesc}</p> <span> {/* 已修改为动态生成链接 */} <a href={`singlepost/id=${id}`}>Read More......</a> </span> </div> ); })} </div> ); }
内容的提问来源于stack exchange,提问作者Deulo
相关产品推荐
相关产品推荐

