首页 > 解决方案 > 当我钻入我的 redux 商店时变得不确定

问题描述

我正在使用 useSelector 来检索我的商店。但是,当我console.log(items)有数据但这样做时,console.log(items.totalAmount)我会变得不确定。

import {useSelector} from 'react-redux';

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

//I'm able to see the data
console.log(items)

记录时的数据

[{"code": "SR71", "description": "Keyboard", "quantity": 1, "selling_price": 166.99, "totalAmount": 166.99}, {"code": "10", "description": "Cement", "quantity": 7, "selling_price": 20, "totalAmount": 140}]
//I get undefined
console.log(items.totalAmount);

任何人都可以解释我做错了什么。

标签: react-reduxredux-toolkit

解决方案


items当你这样做时看起来像这样console.log

[
  {..., "totalAmount": 166.99},
  {..., "totalAmount": 140},
  ...
]

因此,您可以访问totalAmount每个项目,例如:items[0].totalAmount

要获取totalAmount所有项目,您可以使用:

let sum = Array.from(items).reduce((acc, cur) => acc + cur.totalAmount, 0)

我也使用Array.from了,因为没有保证项目是可序列化(正常)数组。(正如您确认它是不可序列化的。)


推荐阅读