TypeError: params.getValue不是函数:MUI DataGrid行ID获取求助
解决MUI X DataGrid中TypeError: params.getValue is not a function的问题
你遇到的错误是因为MUI X DataGrid的renderCell参数在新版本中不再提供getValue方法,直接通过params.row即可访问当前行的完整数据对象。
修改方案
将renderCell里的params.getValue(params.id, "id")替换为params.row.id即可——你已经在rows数组中为每一行定义了id字段,直接从行对象中读取即可。
同时移除actions列中多余的type: "number"配置,该列是操作图标,不需要数字类型定义。
修改后的actions列代码:
{ field: "actions", flex: 0.3, headerName: "Actions", minwidth: 150, sortable: false, renderCell: (params) => { return ( <Link to={`/order/${params.row.id}`}> <LaunchIcon /> </Link> ); }, },
修改后的完整组件代码
import React, { Fragment, useEffect } from "react"; import { DataGrid } from "@mui/x-data-grid"; import "./MyOrders.css"; import { useDispatch, useSelector } from "react-redux"; import { clearErrors, myOrders } from "../../actions/orderAction"; import Loader from "../layout/Loader/Loader"; import { Link } from "react-router-dom"; import { useAlert } from "react-alert"; import { Typography } from "@material-ui/core"; import MetaData from "../layout/MetaData"; import LaunchIcon from "@material-ui/icons/Launch"; const MyOrders = () => { const dispatch = useDispatch(); const alert = useAlert(); const { loading, error, orders } = useSelector((state) => state.myOrders); const { user } = useSelector((state) => state.user); const columns = [ { field: "id", headerName: "Order Id", minwidth: 300, flex: 1 }, { field: "status", headerName: "Status", minwidth: 150, flex: 0.5, }, { field: "itemsQty", headerName: "Items Qty", type: "number", minwidth: 150, flex: 0.3, }, { field: "amount", headerName: "Amount", type: "number", minwidth: 270, flex: 0.5, }, { field: "actions", flex: 0.3, headerName: "Actions", minwidth: 150, sortable: false, renderCell: (params) => { return ( <Link to={`/order/${params.row.id}`}> <LaunchIcon /> </Link> ); }, }, ]; const rows = []; orders && orders.forEach((item) => { rows.push({ itemsQty: item.orderItems.length, id: item._id, status: item.orderStatus, amount: item.totalPrice, }); }); useEffect(() => { if (error) { alert.error(error); dispatch(clearErrors()); } dispatch(myOrders()); }, [dispatch, error, alert]); return ( <Fragment> <MetaData title={`${user.name} - Orders`} /> {loading ? ( <Loader /> ) : ( <div className="myOrdersPage"> <DataGrid rows={rows} columns={columns} pageSize={10} disableSelectionOnClick className="myOrdersTable" autoHeight /> <Typography id="myOrdersHeading">{user.name}'s Orders</Typography> </div> )} </Fragment> ); }; export default MyOrders;
补充说明
params.row是MUI X DataGrid当前版本推荐的行数据访问方式,包含当前行的所有字段,直接通过params.row.字段名即可获取对应值。- 同时移除了代码中未使用的
useParams、useFormAction、useForm导入,精简了代码结构。
内容的提问来源于stack exchange,提问作者Naman kukreja
相关产品推荐
相关产品推荐

