如何在 react-admin 中直接访问 dataProvider?

How do I access the dataProvider directly in react-admin?

如何在react-admin中直接访问dataProvider?我尝试使用 custom dataProvider 但我不知道如何使用它。我的目标是使用地图在输出中显示一个列表。

//Contacts.js

/// --- List ---
export const ContactList = (props) => {
  const classes = useStyles();
  const {data} = useGetList('contacts', props.id);
  return (
     <List className={classes.list}>
      {data.map(({id, name, person}) => (
        <React.Fragment key={id}>
          <ListItem button>
            <ListItemAvatar>
              <Avatar alt="Profile Picture" src={person}/>
            </ListItemAvatar>
            <ListItemText primary={name}/>
          </ListItem>
        </React.Fragment>
      ))}
    </List>
  )
};

//App.js

const App = () => (
  <Admin dataProvider={dataProvider} layout={MyLayout}>
    <Resource
      name="contacts"
      list={ContactList}
      show={ShowContact}
      edit={EditGuesser}
      create={CreateContact}
      icon={ContactPhoneIcon}/>
  </Admin>
);

export default App;

//DataProvider.js

import fakeDataProvider from 'ra-data-fakerest';

const dataProvider = fakeDataProvider({
  contacts: [
    {
      id: 1,
      name: "Tom",
      numbers: {number: '09367371111', type: 'Mobile'},
      person: '/static/images/avatar/5.jpg',

    },
    {
      id: 2,
      name: "Sara",
      numbers: {number: '0936737999', type: 'Home'},
      person: '/static/images/avatar/1.jpg',
    },
  ],
});

export default dataProvider;

Console.log

您必须创建一个自定义列表呈现器,替代 <Datagrid>,并将其作为 <List> 的子项传递:

export const ContactList = (props) => {
  const classes = useStyles();
  return (
     <List className={classes.list}>
        <ContactSimpleList /<
    </List>
  )
};

<List> 组件创建一个 ListContext,并在其中放置 idsdatatotal。因此,您可以通过列表渲染器中的上下文访问此数据:

import { useListContext } from 'react-admin';

const ContactSimpleList = () => {
  const { ids, data } = useListContext();
  return (
    <>
      {ids.map(id => (
          <ListItem key={id} button>
            <ListItemAvatar>
              <Avatar alt="Profile Picture" src={data[id].person}/>
            </ListItemAvatar>
            <ListItemText primary={data[id].name}/>
          </ListItem>
      ))}
    </>
  );
}

此外,您尝试渲染的 SimpleList 看起来很像 react-admin 提供的本机组件:the <SimpleList> component。您可能不需要编写自定义渲染器。