【问题标题】:First element of JSON Object as a KeyJSON 对象的第一个元素作为键
【发布时间】:2021-09-13 08:03:16
【问题描述】:

我正在尝试获取一个名为用户 ID 的对象。

这是我的 JSON:

"createdAt": 1631189580468,
        "custom": {},
        "id": "IDOFCONVO",
        "lastMessage": {
            "attachment": null,
            "createdAt": 1631189829568,
            "custom": {},
            "id": "msg_0OY4vwTcyMh2dkW2SNFPTlhE2E61p",
        },
        "participants": {
            "XXXXX123": {
                "access": "ReadWrite",
                "notify": true
            }
        },
        "photoUrl": null,
        "topicId": null,
        "welcomeMessages": null
    }, 

participants 包含用户的 id 及其属性。我第一次尝试使用<ReferenceManyField>,如下所示:

<ReferenceManyField label="User" target="participants" reference="users">
   <SingleFieldList>
      <ChipField source="name" />
   </SingleFieldList>
</ReferenceManyField>

但它只是从我的用户端点返回每个用户的名称。

我如何指定 Object "participants" 的第一个元素是用户的 id ?

【问题讨论】:

  • 你发布的json里根本没有数组,participants是一个对象。
  • 你能改变你的数据结构吗? ReferenceFields 通常喜欢操作一个扁平的 id 列表。
  • @DoctorAgon 很遗憾没有,我猜我需要创建某种函数来将元素存储为 ID,然后以某种方式注入它?

标签: reactjs json react-admin


【解决方案1】:

尝试使用<FunctionField />,您可以在其中重塑渲染函数中的数据。

<FunctionField
  label='User'
  render={record => {
    if (record === undefined || record === null) return null;
    // Transform the data however you need here
    const newData = Object.keys(record.participants);
    return (
      <ReferenceManyField
        label='User' target='participants' reference='users'
        record={{...record, participants: newData}}
      >
        <SingleFieldList>
          <ChipField source='name' />
        </SingleFieldList>
      </ReferenceManyField>
    )
  }}
/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2014-09-24
    • 2015-05-15
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多