具有 mui-datatables 的对象数组

Array of objects with mui-datatables

向使用 mui-datatables 的人提问。它使用数据作为字符串数组,但是无法加载对象数组并出现此错误:

bundle.js:126379 Uncaught (in promise) TypeError: e.map is not a function

import MUIDataTable from "mui-datatables";

class App extends React.Component {

render() {

const columns = ["Name", "Title", "Location", "Age", "Salary"];

const data = [
  {name: "Gabby George", title: "Business Analyst", location: "Minneapolis", age: 30, salary: "0,000"}      
];

const options = {
  filterType: 'dropdown',
  responsive: 'stacked'
};

return (
  <MUIDataTable 
    title={"ACME Employee list"} 
    data={data} 
    columns={columns} 
    options={options} 
  />
);

//return <div>a</div>;

  }

}

ReactDOM.render(<App />, document.getElementById("root"));

对于偶然发现这个问题的人。事实证明,我没有遗漏任何东西,并且 'mui-datatables' 仅支持数组数组 - 不支持计划中的对象数组。这太糟糕了——我相信组件本身应该按照 API 返回的方式处理数据...哦,我想我必须制作自己的包装器组件来处理它。

为了它的价值,我基本上一直在将我的对象数组映射到简单的内联值数组,如下所示:

const docs = [{"name": "Doc 1", "type": "PDF"}, {"name": "Doc 2", "type": "JPG"}];

<MUIDataTable
    title="Documents"
    data={docs.map(item => {
        return [
            item.name,
            item.type,
        ]
    })}
    columns={Object.keys(docs)}
/>

您可以将它集成到某种包装器组件中,但在一次性情况下添加它非常简单。

注意:如果数据数组为空,MUI Datatables 将不会呈现,所以我经常手动添加我的列,并在之前检查数据的长度映射,否则 return 一个像 [[" "]] 这样的数组。这至少会导致呈现空白 table。

mui-datatables 确实支持对象数组。为了使用对象数组,必须在列数组中指定对象 属性,如下所示:

const columns = [
  { label: "Name", name: "name" },
  { label: "Title", name: "title" }, 
  { label: "Location", name: "location" }, 
  { label: "Age", name: "age" }, 
  { label: "Salary", name: "salary" }
];

const data = [
  {name: "Gabby George", title: "Business Analyst", location: "Minneapolis", age: 30, salary: "0,000"}      
];

const options = {
  filterType: 'dropdown',
  responsive: 'stacked'
};

return (
  <MUIDataTable 
    title={"ACME Employee list"} 
    data={data} 
    columns={columns} 
    options={options} 
  />
);