【问题标题】:TypeError: Cannot read properties of undefined (reading 'type')TypeError:无法读取未定义的属性(读取“类型”)
【发布时间】:2021-11-20 14:21:45
【问题描述】:

我正在尝试在我的预算管理应用程序中平衡收入/支出,但我的余额组件中不断出现此错误:TypeError: Cannot read properties of undefined (reading 'type')。

我认为问题可能与我从减速器带来的重复状态有关,2 次是空数组 [],2 次是满的。我尝试了很多但无法修复它..知道它可能是什么吗??

这是我的余额组件代码:

export default function Balance(){

    const operations = useSelector((state) => state.operations);

    console.log(operations);
    //Shows 4 arrays, 2 empty and 2 full

    const [total, setTotal] = React.useState([]);

    const operationsListCopy = [...operations];

    React.useEffect(() => {

        let entryArray = operationsListCopy.filter((oneOperation) => oneOperation.type == 'INCOME');
        let entryArrayTotal = entryArray?.reduce((amount, item) => item.amount + amount, 0);

        let exitArray = operationsListCopy.filter((oneOperation) => oneOperation.type == 'EXPENSE');
        let exitArrayTotal = exitArray?.reduce((amount, item) => item.amount + amount, 0);
            
        let arrayTotal = entryArrayTotal - exitArrayTotal;

        setTotal(arrayTotal);
    }, [operations]);

【问题讨论】:

  • 当您尝试console.log(operationsListCopy) 时会看到什么?数组中每个json对象的类型是什么。
  • 嗨,我得到了相同的响应:2 个空数组和 2 个满数组。空数组 []、完整数组 [{…}、{…}、{…}]
  • JSON 对象:{id:37,原因:'TEST01',金额:1000,日期:'2021-10-10T03:00:00.000Z',类型:'INCOME'}
  • 2 个空数组和 2 个完整数组日志仅显示您的组件多次重新渲染。真正的问题是,您的数组元素在某些时候没有 type 字段。你能验证你所有的数组元素都有type这个字段吗?
  • 是的,他们都有它,因为添加新操作是强制性的。如果有帮助,我可以告诉你 console.log 答案

标签: reactjs redux typeerror


【解决方案1】:

您应该在访问之前检查 null 或未定义的值。 你可以在这里添加条件

let entryArray = operationsListCopy.filter((oneOperation) => oneOperation?.type == 'INCOME');

这里

 let exitArray = operationsListCopy.filter((oneOperation) => oneOperation?.type == 'EXPENSE');

【讨论】:

  • 完成了这项工作。谢谢@Yaroslav!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2021-11-24
  • 2021-12-20
  • 2021-11-27
  • 2022-01-21
  • 2021-12-04
相关资源
最近更新 更多