React中基于Reducer State计算商品总价并在JSX渲染的实现问询
React useReducer 管理商品选择状态并计算总价实现
1. 定义商品数据与初始状态
先准备符合需求的商品数组和初始选择状态:
// 商品数据示例 const products = [ { id: 'p1', category: 'electronics', name: 'Laptop', price: 1000 }, { id: 'p2', category: 'electronics', name: 'Mouse', price: 50 }, { id: 'p3', category: 'furniture', name: 'Chair', price: 200 }, { id: 'p4', category: 'furniture', name: 'Desk', price: 300 }, ]; // 初始选择状态:分类为顶层键,商品ID为嵌套键,值为选中数量(此示例总价为£500) const initialSelectionState = { electronics: { p1: 0, p2: 0, }, furniture: { p3: 1, p4: 1, }, };
2. 实现useReducer的Reducer函数
处理商品选中数量的增减/设置逻辑,遵循React immutable状态更新规则:
const selectionReducer = (state, action) => { const { category, productId, quantity } = action.payload; switch (action.type) { case 'ADD_QUANTITY': return { ...state, [category]: { ...state[category], [productId]: (state[category][productId] || 0) + 1, }, }; case 'REMOVE_QUANTITY': return { ...state, [category]: { ...state[category], [productId]: Math.max(0, (state[category][productId] || 0) - 1), }, }; case 'SET_QUANTITY': return { ...state, [category]: { ...state[category], [productId]: Math.max(0, quantity), }, }; default: return state; } };
3. 计算选中商品总价的函数
遍历嵌套的选择状态,匹配对应商品价格并累加计算总价:
const calculateTotalPrice = (selectionState, products) => { let total = 0; // 遍历每个分类 Object.entries(selectionState).forEach(([category, productQuantities]) => { // 遍历分类下的商品ID与选中数量 Object.entries(productQuantities).forEach(([productId, quantity]) => { // 匹配对应商品 const targetProduct = products.find(p => p.id === productId && p.category === category); if (targetProduct && quantity > 0) { total += targetProduct.price * quantity; } }); }); return total; };
4. 完整组件实现
整合所有逻辑,在组件中使用useReducer管理状态,计算并渲染总价:
import { useReducer } from 'react'; const ProductSelection = () => { const [selectionState, dispatch] = useReducer(selectionReducer, initialSelectionState); const totalPrice = calculateTotalPrice(selectionState, products); return ( <div> {/* 商品选择区域 */} <div className="product-list"> {products.map(product => ( <div key={product.id} className="product-card"> <h4>{product.name}</h4> <p>单价: £{product.price}</p> <div className="quantity-controls"> <button onClick={() => dispatch({ type: 'REMOVE_QUANTITY', payload: { category: product.category, productId: product.id } })}>-</button> <span>{selectionState[product.category][product.id]}</span> <button onClick={() => dispatch({ type: 'ADD_QUANTITY', payload: { category: product.category, productId: product.id } })}>+</button> </div> </div> ))} </div> {/* 总价展示 */} <div className="total-section"> <h2>选中商品总价: £{totalPrice}</h2> </div> </div> ); }; export default ProductSelection;
内容的提问来源于stack exchange,提问作者peardrops
相关产品推荐
相关产品推荐

