如何以合乎道德的方式从 API 中过滤数据?我正在使用 React JS

How to filter the data from an API in a ethical way? Im using react JS

它工作正常,但我刷新页面时出现此错误 “类型错误:无法读取未定义的属性”

这是我的代码

用于从 API

获取数据
useEffect(() => {
   let isSuscribe = true
   axios.get(myLocalAPI)
       .then(res => 
           {
              if (isSuscribe) {
                  setData(res.data)   
              }
           }
       )
       .catch(err => console.log(err))
return () => isSuscribe = false
})

我有一个 3 组合框用于过滤年、月和日的数据。 我的 API 上的日期格式是这样的“YYYY-MM-DD”

当我过滤数据时,它当然会显示在 DataGrid 上,并且还会获得该日期内的总销售额

实现这是我的代码

对于过滤器Table "Yvalue + "-" + Mvalue + "-" + Dvalue" = YYYY-MM-DD

const filter_table = () =>{

    return Data.filter(
           date=>date.Customer_date
           .toLowerCase()
           .includes(Yvalue + "-" + Mvalue + "-" + Dvalue) )
}

用于筛选并获得总销售额

const filter_data = () => {

    return Data.filter(
        date=>date.Customer_date
        .toLowerCase()
        .includes(Yvalue + "-" + Mvalue + "-" + Dvalue)) //Filter the data first
        .map(e=>e.Customer_total) //When it true map the Total for each data
        .reduce((a,b)=>a+b, 0 ) // Sum the total
}

当我单击按钮并控制两个 return 功能时,它可以正常工作,但是当我在 DataGrid 上实现它时

<DataGrid
columns={columns}
getRowId={(rows) => rows.Customer_ID}
rows={filter_table()} 
pageSize={10}
/>
<span className="featuredTitleperoBlack">{filter_data()} </span>

我收到这个错误 无法读取未定义的属性

请问你们解释为什么我会收到此错误以及过滤数据的合乎道德的方式?

如果有示例代码,我真的很感激,这样我就知道我哪里错了

谢谢!!!

当您刚刚刷新页面时,您还没有数据 - 服务器还没有响应 - 但您已经在尝试过滤它。

一种解决方法是检查数据是否存在。另一种方式是条件链接,像这样

Data?.filter(filterFunction) // if Data is present, it will be filtered