问题描述
我是 React 和 react-admin 的新手。恕我直言,我正在努力实现许多人必须已经完成的简单事情,但我在任何地方都找不到任何类型的教程。
我想在 <List>
组件中每一行的操作按钮(显示/编辑)列表中添加另一个按钮。此按钮将存档记录。
我最后一次尝试看起来像下面的代码。
import React from 'react';
import {
Datagrid,EmailField,List,TextField,ShowButton,EditButton,DeleteButton,CloneButton,} from 'react-admin';
import { makeStyles } from '@material-ui/core/styles';
import ArchiveIcon from '@material-ui/icons/Archive';
const useRowActionToolbarStyles = makeStyles({
toolbar: {
alignItems: 'center',float: 'right',width: '160px',marginTop: -1,marginBottom: -1,},icon_action_button: {
minWidth: '40px;'
},});
const ArchiveButton = props => {
const transform = data => ({
...data,archived: true
});
return <CloneButton {...props} transform={transform} />;
}
const RowActionToolbar = (props) => {
const classes = useRowActionToolbarStyles();
return (
<div className={classes.toolbar}>
<ShowButton label="" basePath={props.basePath} record={props.record} className={classes.icon_action_button}/>
<EditButton label="" basePath={props.basePath} record={props.record} className={classes.icon_action_button}/>
<ArchiveButton {...props} basePath={props.basePath} label="" icon={<ArchiveIcon/>} record={props.record} className={classes.icon_action_button} />
<DeleteButton basePath={props.basePath} label="" record={props.record} className={classes.icon_action_button}/>
</div>
);
};
export const UserList = props => {
return (
<List
{...props}
sort={{ field: 'first_name',order: 'ASC' }}
>
<Datagrid>
<TextField source="first_name"/>
<TextField source="last_name"/>
<EmailField source="email"/>
<RowActionToolbar/>
</Datagrid>
</List>
)
};
显然,这段代码不起作用,因为 <CloneButton>
组件去掉了 id
记录。此外,除非我做错了什么——这是完全可能的——,它会向 GET
端点发出 create
请求。
我在 dataProvider
中使用了不同的路由(后端使用 Django 和 Django rest 框架)。我想将 PATCH
发送到详细信息端点,就像 <Edit>
组件一样。
我也尝试过使用 <SaveButton>
,但它也失败了。
未捕获的类型错误:无法读取未定义的属性“保存” 在 useSaveContext (SaveContext.js:23)
我猜 <SaveButton>
必须在 <SimpleForm>
内?
我想要 <DeleteButton>
的保存行为,即更新列表中的记录,显示记录已存档的通知(带有撤消链接),将请求发送到后端,刷新列表。
任何指导,方向将不胜感激。
解决方法
我不知道这是一个完整的答案,但感觉不仅仅是评论......
您正在尝试存档现有记录,而不是创建全新的记录,对吗? CloneButton 应该用于创建具有新 ID 的新记录(这就是您的 ID 消失的原因),因此您不想在这里使用它。 请注意,我从未使用过 CloneButton。它没有完整记录,所以我可能对它的使用有误。
我认为您应该使用存档按钮中的 useRecordContext 挂钩来获取所有记录数据,包括 id;阅读这个小部分:https://marmelab.com/react-admin/Architecture.html#context-pull-dont-push
而且我不认为转换是您在这里寻找的东西。您将需要使用 dataProvider 钩子之一,我假设 useUpdate: https://marmelab.com/react-admin/Actions.html#useupdate