繁体   English   中英

对象作为 React 子级无效 - 我的 JSON 数据是否损坏?

[英]Objects are not valid as a React child - is my JSON data bad?

我知道在 Stack Overflow 上已经多次询问过这个问题,但其他解决方案似乎对我不起作用。

我正在尝试访问此 JSON 文件中的通知。

我的 JSON 文件: https://dinkyapp.000webhostapp.com/db.json

我的 JSON 文件结构不好吗? 我知道它很大。 在 React 之外的世界中,JSON 文件可以正常工作。 但是在 React 中,无论我是否解析、转换为 arrays 等,它都是行不通的。我应该制作多个较小的文件吗?

在我的示例中,我试图访问通知并在 JSX 中返回它们。

我收到错误消息,“对象作为 React 子项无效”。 我也收到通知。map 不是 function。 这大概是因为被拉出的数据不是数组格式。

我的组件代码:

 import React, { useState, useEffect } from 'react'; import axios from 'axios'; const GetData = () => { let [notifs, setNotifs] = useState([]); useEffect(() => { axios.get('db.json').then((res) => { var data = res.data.clients.clientID_1.notifications; setNotifs(data); }); }, []); const getIDs = notifs.map(item => { return ( <p key={notifs.reqID}>{notifs.text}</p> ) }) return <div>{getIDs}</div>; }; export default GetData;

我几乎要切换回 Vanilla JS,因为我尝试了很多方法。 但我认为可能是我的 JSON 数据不佳。 如果有人可以请建议?

非常感谢

那是因为您正在尝试 map 对象,以简化您的 JSON 可能是

"notifications": [
   {
     "user_id": 1 // move user id here
     "timestamp": 1613777053000,
     "reqID": 100012,
     "seen": true,
     "text": "Aaron F accepted your shift swap"
   },
   {
     "user_id": 2, // move user id here
     "timestamp": 1613777053000,
     "reqID": 100012,
     "seen": true,
     "text": "Aaron F accepted your shift swap"
}]

那么你现在 map 安全

尝试将其更改为:

<p key={item.reqID}>{item.text}</p>

如果查看https://dinkyapp.000webhostapp.com/db.json res.data.clients.clientID_1.notifications它是 object

const notifs = {
    userID_1: [
        {
            timestamp: 1613777053000,
            reqID: 100012,
            seen: true,
            text: 'Aaron F accepted your shift swap',
        },
    ],
    userID_2: [
        {
            timestamp: 1614676200000,
            reqID: 199290,
            seen: true,
            text: 'Sean W approved your Annual Leave request',
        },
        {
            timestamp: 1610719942000,
            reqID: 184828,
            seen: true,
            text: 'Sean W approved your Annual Leave request',
        },
    ],
};

不是数组,因此您需要将其作为 object 使用,例如:

const getIDs = Object.keys(notifs).map(key => {
    return (
        <p key={key}>
            From {key}
            {notifs[key].map(n => (
                <p key={n.reqID}>{n.text}</p>
            ))}
        </p>
    );
});

暂无
暂无

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

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