如何使用admin-on-rest展示同API来源的嵌套子分类数据?
Got it, let's work through this nested category display problem you're hitting. Since your categories and subcategories come from the same API endpoint, ReferenceArrayField won't work here—it's designed for cross-resource references, not self-referential nested data. And if your custom component was showing edit controls, that's probably because you were using form-focused components instead of pure display ones.
Here's a straightforward, recursive component solution that renders your nested categories cleanly without any unwanted edit elements:
Step 1: Build a Recursive Nested Category Component
First, create a reusable component that handles rendering a category and recursively renders its subcategories. This component will only handle display, no edit logic:
import React from 'react'; import { Typography, Box } from '@mui/material'; const NestedCategoryList = ({ categories }) => { // Exit early if there are no categories to render if (!categories || categories.length === 0) return null; return ( <Box component="ul" sx={{ listStyle: 'disc', paddingLeft: 3, margin: 0 }}> {categories.map((category) => ( <li key={category.id} style={{ margin: '8px 0' }}> <Typography variant="body1"> <strong>Code:</strong> {category.code} | <strong>Name:</strong> {category.name} </Typography> {/* Recursively render subcategories if they exist */} {category.subcategories.length > 0 && ( <NestedCategoryList categories={category.subcategories} /> )} </li> ))} </Box> ); }; export default NestedCategoryList;
Step 2: Use the Component in Your Admin View
Now, integrate this component into your Show or List view (whichever you're using to display categories). For example, in a Show view:
import { Show, SimpleShowLayout, TextField } from 'react-admin'; import { Box, Typography } from '@mui/material'; import NestedCategoryList from './NestedCategoryList'; export const CategoryShow = () => ( <Show> <SimpleShowLayout> <TextField source="id" /> <TextField source="code" /> <TextField source="name" /> {/* Add the nested subcategory display */} <Box marginTop={2}> <Typography variant="h6">Subcategories</Typography> <NestedCategoryList categories={record?.subcategories || []} /> </Box> </SimpleShowLayout> </Show> );
Why This Works
- No reference logic needed: We're directly using the nested
subcategoriesdata returned by your API, so we don't rely onReferenceArrayField's cross-resource lookup. - Pure display: The component uses MUI's
TypographyandBoxinstead of form components, so there's no edit-related UI creeping in. - Recursive structure: It handles any depth of subcategories automatically—you don't have to hardcode levels.
If you were seeing edit controls before, double-check that you weren't accidentally using components meant for Edit views (like TextInput) in your display-only views. Sticking to read-only components like TextField or raw Typography will keep the UI clean.
内容的提问来源于stack exchange,提问作者Chetan Gawai

