[英]how to fetch data according id/slug in ReactJS?
我想做的是根据类别 id/slug 获取数据。 例如,我有两个类别(棕色、黑色),如下所示。 如何根据类别 id/slug 获取 blog_set 数据?
我可能是 ReactJs 的新手。 如果有人能帮助我解决我想做的事情,那就太好了。 非常感谢你。
端点网址: http://localhost:8000/api/category
api数据:
[
{
"id": 1,
"title": "brown",
"slug": "brown",
"image": "http://localhost:8000/media/category/bg_1.jpg",
"description": "",
"created_on": "2020-05-08T15:21:02Z",
"status": true,
"blog_set": [
{
"id": 6,
"url": "http://localhost:8000/api/blog_detail/test3",
"title": "test3",
"slug": "test3",
"image": "http://localhost:8000/media/blog/author.jpg",
"description": "test3",
"created_on": "2020-05-13T13:36:45Z",
"status": true,
"category": [
1
]
}
]
},
{
"id": 2,
"title": "black",
"slug": "black",
"image": "http://localhost:8000/media/category/image_7.jpg",
"description": "",
"created_on": "2020-05-08T17:14:43Z",
"status": true,
"blog_set": [
{
"id": 10,
"url": "http://localhost:8000/api/blog_detail/test3",
"title": "Hamid",
"slug": "test3",
"image": "http://localhost:8000/media/blog/person_2_2beHkt1.jpg",
"description": "test",
"created_on": "2020-05-13T14:59:30.855849Z",
"status": true,
"category": [
2
]
}
]
}
]
./src/Category.js
export default class App extends Component{
state = {
bloglist: [],
};
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
try {
const response = await fetch("http://localhost:8000/api/category");
const jsonResponse = await response.json();
this.setState({ bloglist: jsonResponse });
} catch (error) {
console.log(error);
}
};
render(){
{
const { bloglist } = this.state;
if (!bloglist) {
return (
<div>
<h1>loading...</h1>
</div>
);
}
return(
<div>
<h1>Category</h1>
{bloglist.map((bloglist) => (
<div>
<div class="col-md-12">
<div class="blog-entry animate d-md-flex">
<img src={bloglist.image} className="App-logo"/>
<h3 class="mb-2">{bloglist.title}</h3>
<h3 class="mb-2">{bloglist.blog_set.title}</h3>
</div>
</div>
</div>
))}
</div>
);
}
}
}
首先检查 api 是否支持使用 id/slug 获取单个类别。 然后,如果您可以调用 API 并将 id/slug 添加到 fetch API 调用中。 如果您想显示一个带有所选类别的单独页面,您可以启用带有 URL 参数和 react-router-dom 的路由( https://reacttraining.com/react-router/web/example/url-params )。 有了这个,您将在 match 道具中获得 id/slug,这将是this.props.history.match
或使用useParams()
钩子。 然后你可以使用它来调用 API 与选定的 id/slug。
您的用户界面 URL 将如下所示。 http://localhost:3000/category/:id
在浏览器上它看起来像这样http://localhost:3000/category/black
所以当你在你的组件中调用useParams()
钩子时它会像{id} = useParams()
;
现在您可以使用此id
调用单个选择 API 可能如下所示<api_url>:<port>/category/black
或<api_url>:<port>/category?slug=black
通过 query-params 访问深层属性 GET http://localhost:8000/api/category?slug= value
fetchData = async () => {
try {
const response = await fetch("http://localhost:8000/api/category?slug=value");
const jsonResponse = await response.json();
this.setState({ bloglist: jsonResponse });
} catch (error) {
console.log(error);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.