2023-10-30 10:38AM
1. 需要先配置好路由
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import reportWebVitals from './reportWebVitals';
import BlogList from './article/index';
import ArticleDetail from './article/show';
ReactDOM.render(
<BrowserRouter>
<Routes>
<Route exact path="/articles" element={<BlogList />} />
<Route path="/articles/:id" element={<ArticleDetail />} />
</Routes>
</BrowserRouter>,
document.getElementById('root')
);
reportWebVitals();
2. 在列表文件中增加跳转链接:
// src/article/index.js
import { Link } from 'react-router-dom';
……
<Link to={`/articles/${article.id}`}>
<p>
{article.created_at}
{article.title}
</p>
</Link>
3. 增加详情文件:
// src/article/show.js
import React, { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import axios from 'axios';
function ArticleDetail() {
// 初始化为 null,避免初始渲染时显示空的文章
const [article, setArticle] = useState(null);
const { id } = useParams();
// 检查路由参数的值
console.log(id);
useEffect(() => {
const fetchArticle = async () => {
try {
// 修改为你真实的api url
const response = await axios.get(`http://your-api-url/articles/${id}
`);
// 检查返回的数据结构
console.log(response.data);
setArticle(response.data);
} catch (error) {
console.error("请求错误:", error);
}
};
fetchArticle();
}, [id]); // 将 id 添加到依赖数组中,以便在 id 改变时重新获取文章
return (
<div>
<Link to='/articles'>返回</Link><br/>
{/* 添加条件表达式的判断 */}
{article && (
<div>
<h2>{article.title}</h2>
<p>{article.created_at}</p>
<p dangerouslySetInnerHTML={{ __html: article.content }}></p>
</div>
)}
</div>
);
}
export default ArticleDetail;
然后在浏览器打开页面:
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论