如何将列表视图记录传递至Show视图?避免重复请求及过滤配置问询
问题
我有一个记录列表,用户可以通过Show按钮在新页面(Show视图)查看单条记录,这个Show页面里还包含了其他列表视图,这些列表需要用到当前记录的部分字段。想问两个问题:
- 能不能把列表视图里的整条记录直接传递给Show视图,避免再次发起过滤请求?
- 如果没法实现这种传递,必须调用
getList请求的话,过滤参数该配置在哪里?
相关代码示例
App.tsx
<Resource name="record-detail" show={RecordDetail} />
RecordList.tsx
<List> <Datagrid> <ShowButton resource="record-detail" /> ... </Datagrid> </List>
RecordDetail.tsx
const renderAnotherListByRecord = (record: any) => { return <AnotherList resource="another-list" filter={{id: record.id}} /> }; <Show> <SimpleShowLayout>(showing the record)</SimpleShowLayout> <FunctionField render={renderAnotherListByRecord}/> </Show>
回答
1. 能否直接传递整条记录到Show视图?
React Admin默认不支持直接把列表里的完整记录传递到Show页面——因为Show按钮的跳转逻辑是通过URL传递记录ID,Show组件会自动调用getOne接口获取记录详情。如果想绕过这个请求,可以自定义Show按钮的跳转逻辑:
- 用
useHistory钩子,点击时把记录存入location.state:import { useHistory } from 'react-router-dom'; import { Button } from 'react-admin'; const CustomShowButton = ({ record }) => { const history = useHistory(); const handleClick = () => { history.push(`/record-detail/${record.id}`, { record }); }; return <Button onClick={handleClick}>查看详情</Button>; }; - 然后在
RecordDetail组件里,通过useLocation读取state里的记录,替代Show组件自动获取的数据:import { useLocation } from 'react-router-dom'; import { Show, SimpleShowLayout } from 'react-admin'; const RecordDetail = () => { const location = useLocation(); const record = location.state?.record; // 优先用state里的记录,没有的话让Show组件正常发起请求 return ( <Show record={record}> <SimpleShowLayout>(showing the record)</SimpleShowLayout> <FunctionField render={renderAnotherListByRecord}/> </Show> ); };
不过这种方式有个局限:如果用户直接刷新Show页面,location.state会丢失,还是得重新发起请求。
2. 必须调用getList时,过滤参数的配置位置
如果还是需要调用getList请求(比如你代码里的AnotherList),最直接且灵活的方式就是像你现在这样,在使用AnotherList组件时直接传递filter属性:
<AnotherList resource="another-list" filter={{id: record.id}} />
另外还有两种可选方式:
- 在资源定义里配置默认过滤:如果
another-list资源大部分场景都需要按当前记录ID过滤,可以在App.tsx的资源定义里给list组件加默认过滤:
但这种方式依赖父组件传递的record,适用性有限。<Resource name="another-list" list={(props) => <AnotherList {...props} filter={{id: props.record?.id}} />} /> - 自定义dataProvider的
getList方法:在dataProvider层统一处理过滤逻辑,但会影响所有another-list的getList请求,灵活性差,一般不推荐。
最推荐的还是你当前的写法,直接在组件上传递filter参数,按需配置最清晰。
内容的提问来源于stack exchange,提问作者Simon Leung
相关产品推荐
相关产品推荐

