【问题标题】:React: pass Api data to an array | Undefined' is not assignable to type 'GridRowsProp'React:将 Api 数据传递给数组 |未定义的'不可分配给类型'GridRowsProp'
【发布时间】:2021-05-31 02:11:03
【问题描述】:

我正在尝试通过使用 map() 将数据从 api 传递到数组。原因是在带有行的表格中显示数据。我正在使用材质 UI 表。

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:数字;客户名称:字符串;约会:字符串;金额:数量; }[] | undefined' 不可分配给类型 'GridRowsProp'。 类型“未定义”不可分配给类型“GridRowData[]”。 TS2322

结果示例: Image of console result, first is example, second is api data after pushing data into map2

【问题讨论】:

  • 你能补充一个完整的例子吗?
  • 提供了一张带有 console.log 结果的图片,并将代码更改为现在的样子。

标签: reactjs typescript api react-hooks syntax-error


【解决方案1】:
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 ?? []),要么告诉 typescript 你知道这个值不会是 undefinedmap2!。我通常不推荐后者,因为编译器在抱怨该值时会正确执行其工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 2017-07-20
    • 1970-01-01
    • 2016-07-16
    • 2022-08-17
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多