首页 > 解决方案 > 在 React 中将类绑定到 Material-Table 数据

问题描述

是否可以将对象直接传递给材料表数据?如果我直接使用字段定义我的数据,我没有问题,例如

const [data, setData] = useState([{id:'id', name:'name', description:'description', base_price:'10'}]);

但是如果我尝试使用对象类,则会从反应中得到错误。

const [data, setData] = useState([new ProductImpl(1, "productName", "description of product", 12.50, new Date(), 1)]);

此类具有与材料表正在查找的字段相同的字段:

export class ProductImpl implements Product {
    id: number;
    name: string;
    description: string;
    base_price: number;
    posted_date: Date;
    category_id: number;

    constructor (
        id: number,
        name: string,
        description: string, 
        base_price:number, 
        posted_date: Date,
        category_id: number) 
        {
            this.id = id;
            this.name = name;
            this.description = description;
            this.base_price = base_price;
            this.posted_date = posted_date;
            this.category_id = category_id;
        }
}
const ProductTable = (): JSX.Element => {


    const columns = [
        { title: "Id", field: "id" },
        { title: "name", field: "name" },
        { title: "description", field: "description" },
        { title: "base_price", field: "base_price" },
        { title: "posted_date", field: "posted_date" },
        { title: "category_id", field: "category_id" },
    ];

    const [data, setData] = useState([{id:'id', name:'name', description:'description', base_price:'10'}]);
        return (
        <div className="ProductTable">         
           <MaterialTable
             title="Products"
             columns={columns}
             data={data}
           />
        </div>
        );
};
  
  export default ProductTable;

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:

  1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本有关如何调试和修复此问题的提示,请参阅https://reactjs.org/link/invalid-hook-call 。

标签: reactjsmaterial-table

解决方案


推荐阅读