gpt4 book ai didi

javascript - 在 redux 中创建选择器不起作用

转载 作者:行者123 更新时间:2023-12-03 01:41:43 26 4
gpt4 key购买 nike

我正在尝试创建一个选择器:

const getProducts = (state, { productId }) => {
let quantity = 0;
if (state.cart[productId].quantity) {
quantity = state.cart[productId].quantity;
}

return {
accumulatedPrice:
state.cart[productId].quantity * state.products[productId].price,
id: productId,
image: state.products[productId].image,
price: state.products[productId].price,
quantity: quantity
};
};

我正在尝试这样做:

const getLineItem = createSelector([getProducts], products =>
Object.values(products)
);

但我得到的是 [] 而不是 {}

我缺少什么?

最佳答案

一个非常粗略的例子是这样的:

const getProducts = (state) => state.products;
const getCart = (state) => state.cart;
const getProductId = (state, props) => props.productId;


const getLineItem = createSelector(
[getProducts, getCart, getProductId],
(products, cart, productId) => ({
accumulatedPrice: cart[productId].quantity * products[productId].price,
id: productId,
image: products[productId].image,
price: products[productId].price,
quantity: cart[productId].quantity || 0
})
)

如果您愿意并且有getCartProduct,您也可以进一步完善它(与 getProductId 结合)以及 getProduct (再次与 getProductId 结合),但这应该作为一个起点。

关于javascript - 在 redux 中创建选择器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50816449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com