Javascript 如何在ReactJS中获取嵌套api数据?
我试图解决这个问题的是,每当用户点击分类标题,然后用户将重定向到另一个页面,并将看到产品集数据根据分类id或slug。Javascript 如何在ReactJS中获取嵌套api数据?,javascript,reactjs,Javascript,Reactjs,我试图解决这个问题的是,每当用户点击分类标题,然后用户将重定向到另一个页面,并将看到产品集数据根据分类id或slug。 我可能是ReactJs的新手,如果有人能帮我解决我要解决的问题,那就太好了。事先非常感谢你 端点url:“ Api数据: [ { "id": 1, "title": "category01", "slug": "category01", "description": "", "image
我可能是ReactJs的新手,如果有人能帮我解决我要解决的问题,那就太好了。事先非常感谢你 端点url:“ Api数据:
[
{
"id": 1,
"title": "category01",
"slug": "category01",
"description": "",
"image": "http://localhost:8000/media/cat2_KpMV1YQ.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product01",
"id": 1,
"title": "product01",
"slug": "product01",
"image": "http://localhost:8000/media/product2_EMWEgQI.png",
"price": 5,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
]
},
{
"id": 3,
"title": "category03",
"slug": "category03",
"description": "category03 desc..",
"image": "http://localhost:8000/media/cat3_9dal1uP.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product03",
"id": 3,
"title": "product03",
"slug": "product03",
"image": "http://localhost:8000/media/product5.png",
"price": 3,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
{
"url": "http://localhost:8000/api/p/product06",
"id": 5,
"title": "product06",
"slug": "product06",
"image": "http://localhost:8000/media/product6_rkmAlce.png",
"price": 12,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
}
]
}
]
你可以这样做
import { React } from "react";
class categoryListExample extends React.Component{
state={
categoryList:[],
category:''
}
async componentDidMount(){
let res=await fetch("http://localhost:8000/api/p_category")
//assuming you are getting data in response.data
this.setState({categoryList:res.data})
}
categoryChangeHandler=(category)=>{
this.setState({category})
}
render(){
const {categoryList,category}=this.state
if (categoryList.length>0) {
return(
<div>
<ul>
{categoryList.map(category=><li key={category.id} onClick={this.categoryChangeHandler}>{category.title}</li>)}
</ul>
<CategoryComponent category={category.product_set}/>
</div>
)
} else {
return(
<div>
Loading...
</div>
)
}
}
}
export default categoryListExample;
从“React”导入{React};
类categoryListExample扩展React.Component{
陈述={
类别列表:[],
类别:“”
}
异步组件didmount(){
let res=等待获取(“http://localhost:8000/api/p_category")
//假设您在response.data中获取数据
this.setState({categoryList:res.data})
}
categoryChangeHandler=(类别)=>{
this.setState({category})
}
render(){
const{categoryList,category}=this.state
如果(类别列表长度>0){
返回(
{categoryList.map(category=>- {category.title}
)}
)
}否则{
返回(
加载。。。
)
}
}
}
导出默认categoryListExample;
我没有得到你想要的东西,导致堆栈溢出!请拿着(你得到了一个徽章!),四处看看,仔细阅读,特别是我还推荐乔恩·斯基特的。我恐怕不清楚您想在上面做什么,以及您尝试了什么来做。步骤1:获取类别数据。步骤2:获取类别数据中的产品集合数据。第3步:每当用户点击分类标题时,用户就会看到产品集数据@sohanpatiYou然后可以创建CategoryComponent
获取数据后,我通常会看到空白页,我正在与您共享我的远程服务器id。希望您能在live server中帮助我。