首页 > 解决方案 > 我的 React 应用程序将我的 JSON 数据视为数据集合

问题描述

我有一个简单的 fetch 来返回这个数据:

{
  "id": 8,
  "username": "Mr.T",
  "cash": 994999.9,
  "portfolio": [
    {
      "id": 874,
      "stock": {
        "id": 1,
        "name": "Apple",
        "symbol": "AAPL"
      },
      "purchasePrice": 119.05,
      "quantity": 42,
      "purchaseDate": "2020-12-01T09:12:32.591+00:00"
    },
    {
      "id": 11,
      "stock": {
        "id": 1,
        "name": "Apple",
        "symbol": "AAPL"
      },
      "purchasePrice": 170.23,
      "quantity": 200,
      "purchaseDate": "2020-12-01T09:12:22.975+00:00"
    },
    {
      "id": 10,
      "stock": {
        "id": 1,
        "name": "Apple",
        "symbol": "AAPL"
      },
      "purchasePrice": 150.23,
      "quantity": 100,
      "purchaseDate": "2020-12-01T09:12:22.932+00:00"
    }
  ],
  "offers": [
    
  ],
  "stockPerformanceList": [
    {
      "id": 879,
      "stock": {
        "id": 1,
        "name": "Apple",
        "symbol": "AAPL"
      },
      "stockTotalAmount": 342,
      "averagePurchasePrice": 158.1,
      "totalPurchaseValue": 54069.1,
      "stockCurrentPrice": 119.05,
      "stockCurrentValue": 40715.1,
      "stockValueChange": -0.25
    }
  ],
  "portfolioPerformance": {
    "id": 9,
    "portfolioTotalValue": 1035715.0,
    "portfolioTotalStockValue": 40715.1,
    "percentageStockValue": 0.04,
    "percentageCashValue": 0.96
  }
}

如您所见,这是一个简单的对象,这是我的代码片段:

  const [MyData, setMyData] = useState({});

  const FetchData = async () =>{
    const resp = await Axios.get("http://localhost:8080/user/getuseraccount");
    console.log(resp.data);
    setMyData(resp.data);
  }

控制台日志显示我的数据正常,但在设置状态时出现此错误:

Objects are not valid as a React child (found: object with keys {id, stock, stockTotalAmount, averagePurchasePrice, totalPurchaseValue, stockCurrentPrice, stockCurrentValue, stockValueChange}). If you meant to render a collection of children, use an array instead.

知道为什么吗?

它似乎工作了一段时间,但也许我搞砸了,如果您需要更多信息,请告诉我,我会编辑这篇文章

标签: jsonreactjsaxiosfetch

解决方案


您正在尝试渲染一个不允许的对象

<p>{data}</p> //not allowed 

但是,如果出于某种原因要打印对象,可以尝试以下操作

<p>{JSON.stringify(data)}</p> //allowed 

但是您可能想要做的是单独使用对象内部的数据,例如:

<p>Username {data.username}</p>

推荐阅读