当我深入我的 redux store 时得到 undefined

Getting undefined when I drill into my redux store

我正在使用 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);

谁能解释一下我做错了什么。

当你做

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,因为不能保证项目是可序列化(正常)数组。 (正如您确认的那样 non-serializable 。)