React中MaterialUI DataGrid如何展示API返回的嵌套对象值
问题
在React项目中尝试从API获取数据并导入MaterialUI DataGrid组件展示,API返回数据格式如下:
{ data: [ {type: 'PropertyDamage', id: '100', attributes: {identification_number: '3931', damage_date: '2021-04-29', report_date: '2021-06-26'}}, {type: 'PropertyDamage', id: '101', attributes: {identification_number: '3839', damage_date: '2021-01-21', report_date: '2021-08-25'}}, {type: 'PropertyDamage', id: '102', attributes: {identification_number: '3735', damage_date: '2021-04-25', report_date: '2021-10-29'}} ] }
配置的列映射如下,其中id字段可正常显示:
const columns = [ { field: 'id', headerName: "ID" }, { field: "attributes.identification_number", headerName: "Identification Number", headerAlign: "left", align: "left", flex: 1, }, { field: "attributes.damage_date", headerName: "Damage Date", flex: 1, }, { field: "attributes.report_date", headerName: "Report Date", flex: 1, }, ];
使用useEffect和useState获取API数据的代码:
const Dashboard = () => { const [propertydamages, setPropertyDamages] = useState([]); useEffect(() => { const url = "URL"; fetch(url, { method: "GET", withCredentials: true, headers: { 'X-API-Key': 'API Key' } }) .then((response) => response.json()) .then((json) => { setPropertyDamages(json) } ) .catch(function(error) { console.log(error); }); }, []) return ( <Box m="20px"> <DataGrid rows = {propertydamages} columns = {columns} /> </Box> ); };
尝试通过"attributes.identification_number"这类嵌套字段名取值时无法正常显示,仅写"attributes"会显示[object object],如何正确获取并展示identification_number、damage_date和report_date?
解决方法
方案1:转换数据结构
在将API返回的数据存入state前,展开嵌套的attributes字段,把需要的属性提升到顶层:
修改fetch的回调逻辑:
.then((json) => { // 提取API返回的data数组,并转换每条数据的结构 const transformedRows = json.data.map(item => ({ id: item.id, identification_number: item.attributes.identification_number, damage_date: item.attributes.damage_date, report_date: item.attributes.report_date })); setPropertyDamages(transformedRows); })
同步更新列配置,使用顶层字段名:
const columns = [ { field: 'id', headerName: "ID" }, { field: "identification_number", headerName: "Identification Number", headerAlign: "left", align: "left", flex: 1, }, { field: "damage_date", headerName: "Damage Date", flex: 1, }, { field: "report_date", headerName: "Report Date", flex: 1, }, ];
方案2:使用DataGrid的valueGetter属性
无需修改原始数据结构,直接在列配置中通过valueGetter函数读取嵌套字段:
更新列配置:
const columns = [ { field: 'id', headerName: "ID" }, { field: "identification_number", headerName: "Identification Number", headerAlign: "left", align: "left", flex: 1, valueGetter: (params) => params.row.attributes.identification_number }, { field: "damage_date", headerName: "Damage Date", flex: 1, valueGetter: (params) => params.row.attributes.damage_date }, { field: "report_date", headerName: "Report Date", flex: 1, valueGetter: (params) => params.row.attributes.report_date }, ];
关键修正:传递正确的行数据
原代码中setPropertyDamages(json)存在错误,API返回的行数组在json.data字段中,需要修正为:
.then((json) => { setPropertyDamages(json.data); })
内容的提问来源于stack exchange,提问作者Omkar Biradar
相关产品推荐
相关产品推荐

