繁体   English   中英

从 axios 响应 object 渲染对象数组

[英]rendering an array of objects from the axios response object

我正在尝试在从 axios 返回的响应 object 中渲染对象数组。

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;

我在 render 方法中没有收到 {item.name} 的任何错误,但是一旦我输入 {item.posts} 我收到此错误错误:对象作为 React 子项无效(找到:object,带有键 {_id,价格})。 如果您打算呈现子项集合,请改用数组。

如果您想将整个数组呈现为文本,则需要对其进行解析,而 a-kon 的答案应该可以完成这项工作。

但是如果你想为每个帖子渲染一个元素(例如一个 div),你也需要使用 map function。

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>
    );

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

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM