[英]How to fetch inner API data in ReactJS?
What I am trying to do is fetch the inner data of blog_set
.我想做的是获取
blog_set
的内部数据。 But in my case, I'm getting a null
value (usually nothing is output).但就我而言,我得到了一个
null
值(通常没有输出)。
Is this the correct way to get the value: {bloglist.blog_set.title}
?这是获取值的正确方法:
{bloglist.blog_set.title}
吗?
api-data: api数据:
[
{
"url": "http://localhost:8000/api/category/brown",
"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
]
}
]
}
]
./src/Category.js ./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;
return(
<div>
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{bloglist.blog_set.title}</h3>
</div>
))}
</div>
);
}
}
}
blog_set
is an array so it does not have an attribute/memeber/item called title
. blog_set
是一个数组,因此它没有名为title
的属性/memeber/item。 You should define at what index you want the data.您应该定义您想要数据的索引。
bloglist.blog_set[0].title
Or iterate over blog_set
too或者也迭代
blog_set
blog_set
is an array. blog_set
是一个数组。 In order to iterate it, use map
and {title}
.为了对其进行迭代,请使用
map
和{title}
。 In each iteration of your blog_set
object, there is a key named title
(destructured object).在
blog_set
object 的每次迭代中,都有一个名为title
的键(解构对象)。
<div>
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{blog_set.map(({title})=>title))}</h3>
</div>
))}
</div>
As bloglist is also an array you need to use one more .map()
or as bloglist[0].blog_set[0].title
由于 bloglist 也是一个数组,您需要再使用一个
.map()
或bloglist[0].blog_set[0].title
Example:例子:
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{bloglist.blog_set.map(i=> i.title)}
</h3>
</div>
))}
blogList.map() will iterate the parent Array of objects to get blog_set and blog_set.map() will now iterate the blog_set to get list title blogList.map() 将迭代父对象数组以获取 blog_set 和 blog_set.map() 现在将迭代 blog_set 以获取列表标题
{bloglist.map((bloglist) =>(
<div>
<h3 class="mb-2">{bloglist.blog_set.map((list)=>( list.title)}</h3>
</div>)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.