在React中渲染嵌套对象的问题

时间:2020-10-18 23:36:35

标签: reactjs jsx

我正在尝试从REST API呈现响应。我可以获取数据,并且在render部分中渲染flat属性时没有任何问题。但是,当我尝试渲染嵌套对象时,出现错误。 错误显示:(错误:对象作为React子对象无效(找到:带有键{amount,currency}的对象。)如果要渲染子对象的集合,请改用数组。)

邮递员和console.log的响应是这样的。

{
    "totalCost": {
        "amount": 36500,
        "currency": "USD"
    },
    "title": "Hydraulic Services",
    "lineItemCount": 1,
    "submitDate": 1602810449329
}

我对titlelineItemCountsubmitDate没什么疑问。但是当我尝试渲染totalCost时,出现了上面列出的错误。我还像这样单独尝试了它的嵌套属性。

 <li> Total Cost : {items.totalCost.amount}</li> 
   <li> Total Cost : {items.totalCost.currency}</li>

我的完整代码在这里。

import React, { Component } from "react";
import axios from "axios";
import "./App.css";

class PenApprovals extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      errorMessage: ""
    };

  }

  componentDidMount() {
    const headers = {
      "Content-Type": "application/json",
      apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
      Authorization: "Bearer 571806a2-93c6-40f8-a35e-4056d014c7f4",
    };

      let url =
      "/api/approval/v1/prod/items/IN34623?realm=xyz";
    axios
      .get(url, { headers })
      .then((res) => {
        this.setState({ items: res.data });
      })
      .catch((error) => {
        this.setState({ errorMessage: error.message });
        console.log(error);
      });
  }


  render() {
    const { items } = this.state;

    return (
      <div>
        {this.state.errorMessage && (
          <h3 className="error">{this.state.errorMessage}</h3>
        )}

        <h1>Record Details</h1>
        <ul>
        {console.log({items})}
              <li>{items.uniqueName}</li>
              <li>Title: {items.title}</li>
              <li>Line Item Count: {items.lineItemCount}</li>
              <li>Submit Date: {items.submitDate}</li>
              {/*  
                All of these three not working. I have tried seprately as well.
                <li> Total Cost : {items.totalCost}</li>  // not working
                <li> Total Cost : {items.totalCost.amount}</li> 
                <li> Total Cost : {items.totalCost.currency}</li> 

                //Postman & console.log Output
                {
                    "totalCost": {
                        "amount": 110.67,
                        "currency": "AUD"
                    },
                    "title": "Stationery order 28/8/17",
                    "lineItemCount": 1,
                    "submitDate": 1602027827752
                 }
              */}
        </ul>   
      </div>
    );
  }
}
export default PenApprovals;

1 个答案:

答案 0 :(得分:1)

这是初始化items的方式:

this.state = {
  items: [],
  errorMessage: ""
};

您的API调用是异步的。这就是为什么在将结果分配给items之前组件将呈现的原因。

使用null对其进行初始化。然后,如果它仍然为空,请不要尝试渲染它:

render() {
  const { items, errorMessage } = this.state;
  
  if (!items && !errorMessage) {
    return null; // or a loading indicator
  }

  return (
    <div>
      ...
    </div>
  );
}

顺便说一句:您要在errorMessage2中设置errorMessage而不是axios.catch

相关问题