reactjs 对象Map数组不是函数

szqfcxe2  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(158)

I'm new to React, I'm pulling an API, which is filled with an array of objects. When trying to map it I get following error: "Uncaught TypeError: benchmarkData.map is not a function"
当我得到错误时,它实际上完成了工作(当我记录它时,我得到了询问的结果),它只是阻止加载其他元素。
这是我的API的外观:

[
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "412",
"DEGEMAT": "235",
"DEGEMGW": "97.7",
"DEGEMMB": "3.39",
"DEGEMNV": "64.1",
"DEGEMSD": "13.2",
"DEGEMVD": "71.3",
"DEJAART": "2022",
"DELTMCE": "-",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "436",
"DEGEMAT": "233",
"DEGEMGW": "120.1",
"DEGEMMB": "3.38",
"DEGEMNV": "64.2",
"DEGEMSD": "13.2",
"DEGEMVD": "71.4",
"DEJAART": "2022",
"DELTMCE": "ALL",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "22",
"DEGEMAT": "213",
"DEGEMGW": "99.9",
"DEGEMMB": "3.23",
"DEGEMNV": "64.9",
"DEGEMSD": "12.7",
"DEGEMVD": "72.8",
"DEJAART": "2022",
"DELTMCE": "BBC",
"DEWEENR": "1"
}
]

这是我的React代码:

useEffect(() => {
    if (benchmarkData) {
      setSupplierHasData(true);
      let loadingplaceFilter = [];
      const loadingPlaces = [];
      benchmarkData.map(item => { //!start of requested question code
        if(item.type === "drlvbmk") {
           loadingPlaces.push(item.DELPLCE, item.DELTMCE, item.DEELTCE)
        }
      }
      ); //!end of requested question code
      console.log(loadingPlaces);

      const uniqueLoadingplaces = [];
      loadingPlaces.map((item) => {
        var findItem = uniqueLoadingplaces.find((x) => x === item);
        if (!findItem) uniqueLoadingplaces.push(item);
      });
      console.log('uniqueloadingplaces', uniqueLoadingplaces);

      setFilters({
        ...filters,
        loadingplaces: loadingplaceFilter,
      });

      setFilterData(true);

  }, [benchmarkData]);

提取API:

useEffect(() => {
    const fetchBenchmarkData = async () => {
      setFetchNewData(false);
      console.log('current user active id :', suppliersState.suppliers.activeID, "current user active uuid:  ", suppliersState.suppliers.activeUUID);
      try  {
        await axios
      
          .get(
            `https://bpg-ap.ddev.site/jsonapi/benchmarking_get_data?supplierid=${suppliersState.suppliers.activeID}&date_from=1&date_to=2022`
          )
          .then(res => {
            setBenchmarkData(res.data);
            console.log('BENCHMARKINGRESULTAAT : ', res.data);
          });
        } catch(error) {
          setSupplierHasData(false);
          setChartData({});
            console.log(error);
        }
    };
    if (benchmarkData === null) {
      console.log('useEffect fired, fetch benchmarkData', benchmarkData);
      fetchBenchmarkData();
    } 
  }, [benchmarkData, suppliersState.suppliers.activeID]);

记录基准数据结果:

我希望任何人都能帮助我解决这个问题

xdyibdwo

xdyibdwo1#

看起来您误解了UseEffect的工作方式,如果您在组件内部使用此Hook,则会在每次重新呈现组件时告诉UseEffect内部的React代码运行,因此您无需检查benchmarkData是否为“nul”即可运行函数,因为BenchmarkData初始状态为null,并且当你第一次运行组件时,它将总是运行此代码。现在,如果你将BenchemarkData放入依赖项中,则意味着每次Benchemark的状态更改时,UseEffect中的代码都将运行。

useEffect(() => {
    const fetchBenchmarkData = async () => {
      setFetchNewData(false);
      console.log('current user active id :', suppliersState.suppliers.activeID, "current user active uuid:  ", suppliersState.suppliers.activeUUID);
      try  {
        await axios
           .get(
            `https://bpg-ap.ddev.site/jsonapi/benchmarking_get_data?supplierid=${suppliersState.suppliers.activeID}&date_from=1&date_to=2022`
          )
          .then(res => {
            setBenchmarkData(res.data);
            console.log('BENCHMARKINGRESULTAAT : ', res.data);
          });
        } catch(error) {
          setSupplierHasData(false);
          setChartData({});
            console.log(error);
        }
    };
    fetchBenchmarkData();
  }, [benchmarkData, suppliersState.suppliers.activeID]); //UseEffect will run each time benchmarkData, OR suppliersState.suppliers.activeID state change.

现在,根据您想要做的事情,如果您想在组件第一次呈现时运行此函数仅一次,则也可以不将任何内容放入依赖项中,并且即使您像这样重新呈现组件,它也永远不会再次运行:

useEffect(() => {
fetchBenchmarkData();
 }, []); // this will run the function only once the component render the 1st time

在您的情况下,如果基准测试的初始状态为null,则不能使用map循环,因此不能使用挂钩useEffect,因为无论BenchmarkData是否为null,它都会在第一次渲染时触发。现在我不知道在获取数据和Map数据之间发生了什么,如果数据在单独的组件中还是在同一个组件中,但请再次尝试(我简化了,因为我不知道您的其他变量):

if (benchmarkData) {
      console.log(benchmarkData) // check the log here if the Data is present, and make sure the data is in an Array in order to use Map
      //...
      
      const loadingPlaces = [];
      benchmarkData.map(item => { 
        if(item.type === "drlvbmk") {
           loadingPlaces.push(item.DELPLCE, item.DELTMCE, item.DEELTCE)
        }
      };
      console.log(loadingPlaces);
     //...

相关问题