从 Axios 响应对象呈现对象数组



我正在尝试在响应对象中渲染一个对象数组,im从axios返回。

import React, { Component } from "react";
import axios from "axios";
class Bids extends Component {
state = {
adminPosts: [],
};
componentDidMount() {
this.getPosts();
}
getPosts = async () => {
let posts = await axios.get(
"http://localhost:3001/api/posts/admin"
);
let allPosts = posts.data;
this.setState({ adminPosts: allPosts });
};

render() {
let items = [...this.state.adminPosts];
/*
This is the item array from above
[
{
_id: 1,
name: "john",
posts: [
{ _id: 1000, price: "100" },
{ _id: 1001, price: "300" },
{ _id: 1002, price: "160" },
],
},
{
_id: 2,
name: "jack",
posts: [{ _id: 1004, price: "400" }],
},
{
_id: 3,
name: "jill",
posts: [],
},
];
*/
return (
<div>
<h1>hello from Sales</h1>
{items.map((item) => (
<li key={item._id}>
<div className="container">
<p> Name: {item.name}</p>
<p> posts: {item.posts}</p> //React will not render this array of objects
</div>
</li>
))}
</div>
);
}
}
export default Bids;

我在渲染方法中没有收到任何 {item.name} 错误,但一旦我输入 {item.posts},我就会收到此错误 错误:对象作为 React 子项无效(找到:具有键 { _id, price} 的对象(。如果要呈现子项集合,请改用数组。

如果你想将整个数组渲染为文本,你需要解析它,来自a-kon的答案应该可以完成这项工作。

但是如果你想在每个帖子中渲染一个元素(例如一个div(,你也需要使用map函数。

return (
<div>
<h1>hello from Sales</h1>
{items.map((item) => (
<li key={item._id}>
<div className="container">
<p> Name: {item.name}</p>
<div> 
<p>posts:</p>
{item.posts.map((post) =>(<div>
<span>id: {post._id} </span>
<span>price: {post.price}</span>
</div>))}
</div>
</div>
</li>
))}
</div>
);

看来你已经熟悉地图了,你可以再次使用它:

<p> posts: <ul>{item.posts.map(e => <li key={e._id}>price: {e.price}</li>)}</ul></p>

您正在尝试在此处posts渲染数组:<p> posts: {item.posts}</p> //React will not render this array of objects

不能呈现对象数组。但是你可以渲染它的 JSON 表示形式:<p> posts: {JSON.stringify(item.posts)}</p>

最新更新