从 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,价格})。如果要呈现子级集合,请改用数组。


猛跑小猪
浏览 142回答 3
3回答

心有法竹

如果要将整个数组呈现为文本,则需要解析它,并且来自a-kon的答案应该可以完成工作。但是,如果您想为每个帖子渲染一个元素(例如div),您也需要使用map函数。return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <h1>hello from Sales</h1>&nbsp; &nbsp; &nbsp; &nbsp; {items.map((item) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li key={item._id}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className="container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p> Name: {item.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>posts:</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {item.posts.map((post) =>(<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>id: {post._id} </span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>price: {post.price}</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>))}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );

扬帆大鱼

看来你已经熟悉地图了,你可以再次使用它:<p>&nbsp;posts:&nbsp;<ul>{item.posts.map(e&nbsp;=>&nbsp;<li&nbsp;key={e._id}>price:&nbsp;{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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript