按引用字段对列表进行排序 react-admin

Sorting a list by a referenced field react-admin

我开始使用 react-admin 并且基本上工作正常。但是我在使用 ReferenceField.

时遇到了一些麻烦

REST API 我正在呼叫 returns 例如以下 JSON 数据:

/语言

{
  "language": [
    {
      "id": 0,
      "name": "Language #0"
    },
    {
      "id": 1,
      "name": "Language #1"
    },
    {
      "id": 2,
      "name": "Language #2"
    },
    {
      "id": 3,
      "name": "Language #3"
    }
  ]
}

/myreferences

{
  "myreferences": [
    {
      "id": 0,
      "langauge": {
        "id": 0,
        "name": "Language #0"
      },
      "name": "My reference #0"
    },
    {
      "id": 1,
      "langauge": {
        "id": 1,
        "name": "Language #1"
      },
      "name": "My reference #1"
    },
    {
      "id": 2,
      "langauge": {
        "id": 2,
        "name": "Language #2"
      },
      "name": "My reference #2"
    }
  ]
}

这就是在 react-admin 中映射它的方式。

export const LanguageList = props => (
  <List
    title="Languages"
    sort={{ field: "name", order: "ASC" }}
    filters={<LanguageFilter/>}
    {...props}
  >
    <Datagrid>
      <NumberField source="id" label="ID" />
      <TextField source="name" label="Name" />
      <EditButton />
    </Datagrid>
  </List>
); 

export const MyReferenceList = props => (
  <List
    title="My References"
    sort={{ field: "name", order: "ASC" }}
    filters={<MyReferenceFilter />}
    {...props}
  >
    <Datagrid>
      <NumberField source="id" label="ID" />
      <TextField source="name" label="Name" />
      <ReferenceField source="langauge.id" reference="language" label="Language">
        <TextField source="name" />
      </ReferenceField>
      <EditButton />
    </Datagrid>
  </List>
);

我的问题是引用显示正确,但是当我单击引用语言名称的列时,react-admin 按语言 ID 而不是名称排序。

我需要调整什么才能按名称排序?

<ReferenceField> 组件接受一个 sortBy 属性,它指定用于排序的字段而不是 source。所以在你的情况下,你可以写:

      <ReferenceField source="language.id" sortBy="language.name" reference="language" label="Language">
        <TextField source="name" />
      </ReferenceField>

这在 React-admin 文档中有解释:

https://marmelab.com/react-admin/Fields.html#referencefield