React:将 Api 数据传递给数组 | Undefined' 不可分配给类型 'GridRowsProp'
React: pass Api data to an array | Undefined' is not assignable to type 'GridRowsProp'
我正在尝试通过使用 map() 将数据从 api 传递到数组。原因是要在带有行的表格中显示数据。我正在使用 material UI table.
const array1 = data?.interface_here;
const map2 = array1?.map(x => ({ id: x.id, customer_name: x.customer_name, appointment: x.appointment, amount: x.amount }));
//This is how the data-grid wants me to do it
const rows = [
{ id: 1, customer_name: "y", appointment: '12:30', amount: 35 },
{ id: 2, customer_name: "w", appointment: '12:30', amount: 35 },
];
console.log(rows);
console.log(map2);
// {id: 30, customer_name: "Hello", appointment: "19.05.2021", amount: 650}
return (
<Body>
<div style={{ height: 400, width: '100%' }}>
<DataGrid rows={map2} columns={columns} pageSize={5} checkboxSelection />
</div>
但是当我尝试将 rows={rows} 更改为 rows={map2} 时,出现错误:
输入'{ id: number; customer_name:字符串;约会:字符串;数量:数量; }[] | undefined' 不可分配给类型 'GridRowsProp'。
类型 'undefined' 不可分配给类型 'GridRowData[]'。 TS2322
结果示例:
Image of console result, first is example, second is api data after pushing data into map2
const map2 = array1?.map(x => ({ id: x.id, customer_name: x.customer_name, appointment: x.appointment, amount: x.amount }));
您正在使用可选链接来推迟处理 array1
可能未定义的值。这意味着潜在的 undefined
-ness 会传递给 map2
,其类型签名将类似于:
{id: number; customer_name: string; appointment: string; amount: number}[] | undefined
您需要将其默认为某个合理的值 (map2 ?? []
),或者告诉打字稿您 知道 这个值不会 undefined
:map2!
。我通常不推荐后者,因为编译器在抱怨该值时正确地完成了它的工作。
我正在尝试通过使用 map() 将数据从 api 传递到数组。原因是要在带有行的表格中显示数据。我正在使用 material UI table.
const array1 = data?.interface_here;
const map2 = array1?.map(x => ({ id: x.id, customer_name: x.customer_name, appointment: x.appointment, amount: x.amount }));
//This is how the data-grid wants me to do it
const rows = [
{ id: 1, customer_name: "y", appointment: '12:30', amount: 35 },
{ id: 2, customer_name: "w", appointment: '12:30', amount: 35 },
];
console.log(rows);
console.log(map2);
// {id: 30, customer_name: "Hello", appointment: "19.05.2021", amount: 650}
return (
<Body>
<div style={{ height: 400, width: '100%' }}>
<DataGrid rows={map2} columns={columns} pageSize={5} checkboxSelection />
</div>
但是当我尝试将 rows={rows} 更改为 rows={map2} 时,出现错误: 输入'{ id: number; customer_name:字符串;约会:字符串;数量:数量; }[] | undefined' 不可分配给类型 'GridRowsProp'。 类型 'undefined' 不可分配给类型 'GridRowData[]'。 TS2322
结果示例: Image of console result, first is example, second is api data after pushing data into map2
const map2 = array1?.map(x => ({ id: x.id, customer_name: x.customer_name, appointment: x.appointment, amount: x.amount }));
您正在使用可选链接来推迟处理 array1
可能未定义的值。这意味着潜在的 undefined
-ness 会传递给 map2
,其类型签名将类似于:
{id: number; customer_name: string; appointment: string; amount: number}[] | undefined
您需要将其默认为某个合理的值 (map2 ?? []
),或者告诉打字稿您 知道 这个值不会 undefined
:map2!
。我通常不推荐后者,因为编译器在抱怨该值时正确地完成了它的工作。