【问题标题】:How to fix TypeError: Cannot read property of undefined?如何修复 TypeError:无法读取未定义的属性?
【发布时间】:2021-10-03 04:43:52
【问题描述】:

我的 UI 崩溃并出现以下错误:

TypeError: Cannot read property 'filter' of undefined

at v (helper.js:16)
at i (lodash.min.js:9)
at t (lodash.min.js:59)
at value (CheckAll.js:15)

这是 helper.js 代码的 sn-p:

export const updatedChecked = (items, checked) => items.map(item => ({ ...item, checked }));

export const filterChecked = (items, checked) => items.filter(item => item.checked === checked);

export const moveAtTheTop = (items, itemIds) => pureReverse(itemIds).reduce((acc, v) => {
 const toCutIndex = acc.findIndex(item => item.id === v);
 const toCut = acc.splice(toCutIndex, 1)[0];
 toCut.checked = true;
 acc.unshift(toCut);
 return acc;
}, updateChecked(items, false));

export const normalizeSrcItems = items => filterChecked(items, true).map(item => item.id);

【问题讨论】:

  • 你在哪里打电话给normalizeSrcItems,你给它传递了什么?
  • 您需要弄清楚为什么items 未定义。你可以用很多不同的方式来修补它,比如normalizeSrcItems 中的默认items arg 为[]items?.filter(...)etc,但这实际上取决于在你的应用程序中,items 未定义是否有效,如果它是有效的,你需要对项目进行无效检查(if (items) 等),或者如果它不是一个有效的场景,那么你的代码中有一个错误,itemsundefined,而它不应该是

标签: javascript reactjs frontend typeerror


【解决方案1】:

这可能是因为您在调用normalizeSrcItems 时在items 参数中发送了undefined。你需要在你调用它的地方检查它

if (items) {
  normalizeSrcItems(items)
}

,或者检查一下为什么你有空物品,也许你拿错了

【讨论】:

    【解决方案2】:

    显然,调用

    items.filter(...)
    

    看起来项目未定义。快速修复是:

    (items || []).filter(...)
    

    但它可能无法解决问题,为什么项目未定义。

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2021-10-28
      • 2022-01-12
      • 2022-11-22
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      相关资源
      最近更新 更多