json - 我的 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.
知道为什么吗?
它似乎工作了一段时间,但也许我搞砸了,如果您需要更多信息,请告诉我,我会编辑这篇文章
解决方案
您正在尝试渲染一个不允许的对象
<p>{data}</p> //not allowed
但是,如果出于某种原因要打印对象,可以尝试以下操作
<p>{JSON.stringify(data)}</p> //allowed
但是您可能想要做的是单独使用对象内部的数据,例如:
<p>Username {data.username}</p>
推荐阅读
- r - 如何使用 R 将区域从 shapefile 传输到 netcdf 文件?
- sql-server - 为什么我会收到此错误:System.ArgumentNull 异常:值不能为空。(参数“连接字符串”)ASP.NET Core
- file - 在 R 中解码 sl2 文件的声纳视图的探测数据
- c - 我的程序不打印任何内容并失败
- java - 无法使用 Rest Template 下载 REST API 生成的 zip 文件
- huggingface-transformers - 用于问答的 Huggingface 管道
- javascript - 节点动态导出和顶级等待单文件环境
- google-cloud-platform - cloudshell 中已安装客户端库的位置
- reactjs - React.ComponentProps 的 React 语法问题
- model - 在搅拌机中,当我尝试导出到 gltF2.0 时出现错误