我是 immutable.js 的新手,在我的一生中,我无法弄清楚如何在我的状态对象上使用“fromJS”来迭代结果形式的 map /列表。
在下面的示例中,我将如何计算购物车的总数? 购物车语法为:{productId: quantity, productId: quantity, productId.. etc
const INITIAL_STATE = fromJS({
products: [
{id: 1, name:'spaghetti', price: 25.00},
{id: 2, name:'gold', price: 20.00},
{id: 3, name:'rake', price: 15.00},
{id: 4, name:'car', price: 10.00},
{id: 5, name:'falcon', price: 5.00}
],
cart: {1: 4, 3: 7}
})
这里如何遍历不可变对象(immutable对象)?此处介绍的方法对我初级的眼睛来说很详细:https://facebook.github.io/immutable-js/docs/#/List/keys
我想我找到了一个解决方案,虽然有点乱:
const total = () => {
let total =0
state.get('products')
.filter( p => {
return state.get('cart')
.has(p.get('id').toString())
})
.map( p => {
total += state.get('cart')
.get(p.get('id').toString())
* p.get('price')
})
return total
}
最佳答案
以下会起作用,它稍微简洁一些。
const total = state.get('cart').reduce((total, quantity, id) => {
const price = state.get('products').find(product => product.get('id') == id).get('price');
total += price * quantity;
return total;
}, 0);
关于javascript - 如何遍历 immutable.js 对象/ map /列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37671739/