在React-Redux中添加eShop(电子商店)中的商品数量,通常涉及到以下几个基础概念:
在eShop中,你可以使用Redux来管理购物车中商品的数量。例如,当用户增加或减少商品数量时,可以通过分发相应的动作来更新Redux store中的状态。
以下是一个简单的示例,展示如何在React-Redux中添加商品数量:
// actions.js
export const INCREMENT_QUANTITY = 'INCREMENT_QUANTITY';
export const DECREMENT_QUANTITY = 'DECREMENT_QUANTITY';
export const incrementQuantity = (productId) => ({
type: INCREMENT_QUANTITY,
payload: productId,
});
export const decrementQuantity = (productId) => ({
type: DECREMENT_QUANTITY,
payload: productId,
});
// reducers.js
import { INCREMENT_QUANTITY, DECREMENT_QUANTITY } from './actions';
const initialState = {
products: [
{ id: 1, name: 'Product 1', quantity: 0 },
{ id: 2, name: 'Product 2', quantity: 0 },
],
};
const cartReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT_QUANTITY:
return {
...state,
products: state.products.map((product) =>
product.id === action.payload
? { ...product, quantity: product.quantity + 1 }
: product
),
};
case DECREMENT_QUANTITY:
return {
...state,
products: state.products.map((product) =>
product.id === action.payload && product.quantity > 0
? { ...product, quantity: product.quantity - 1 }
: product
),
};
default:
return state;
}
};
export default cartReducer;
// Product.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { incrementQuantity, decrementQuantity } from './actions';
const Product = ({ productId }) => {
const dispatch = useDispatch();
const product = useSelector((state) =>
state.products.find((p) => p.id === productId)
);
return (
<div>
<h3>{product.name}</h3>
<button onClick={() => dispatch(decrementQuantity(productId))}>-</button>
<span>{product.quantity}</span>
<button onClick={() => dispatch(incrementQuantity(productId))}>+</button>
</div>
);
};
export default Product;
问题:为什么Redux store中的状态没有更新?
原因:
connect
函数或者useSelector
和useDispatch
钩子来连接组件和Redux store。解决方法:
connect
函数:import { connect } from 'react-redux';
import { incrementQuantity, decrementQuantity } from './actions';
const mapStateToProps = (state) => ({
products: state.products,
});
const mapDispatchToProps = {
incrementQuantity,
decrementQuantity,
};
export default connect(mapStateToProps, mapDispatchToProps)(Product);
或者使用React Hooks:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { incrementQuantity, decrementQuantity } from './actions';
const Product = ({ productId }) => {
const dispatch = useDispatch();
const product = useSelector((state) =>
state.products.find((p) => p.id === productId)
);
// ... 组件代码
};
export default Product;
通过以上步骤,你应该能够在React-Redux中成功添加eShop中的商品数量。如果遇到其他问题,可以参考Redux官方文档和React-Redux官方文档获取更多信息。
DB・洞见
taic
taic
Elastic 实战工作坊
Elastic 实战工作坊
开箱吧腾讯云
云+社区技术沙龙[第27期]
开箱吧腾讯云
云+社区技术沙龙[第22期]
腾讯云GAME-TECH沙龙
云+社区技术沙龙 [第30期]
领取专属 10元无门槛券
手把手带您无忧上云