React使用useReducer修改state后UI未更新问题求助
问题核心
你在Cart组件中渲染手机列表时,遍历的是初始的静态Phones数据源,而非useReducer托管的state.phones状态数组。即使reducer逻辑正确更新了状态,渲染依赖的数据源始终没有变化,因此UI不会同步刷新。
修复方案
1. 调整渲染数据源
将Cart组件中Phones.map替换为state.phones.map
2. 补全reducer逻辑
补充decrease操作分支以及默认返回逻辑,避免未匹配的action类型导致state被置为undefined
修复后完整代码
const initialState = { phones: [...Phones] }; const reducer = (state, action) => { switch(action.type) { case "increase": const newPhones = state.phones.map(phone => { if (phone.id === action.payload) { return { ...phone, quantity: phone.quantity + 1 }; } return phone; }); return { ...state, phones: newPhones }; case "decrease": const decreasedPhones = state.phones.map(phone => { if (phone.id === action.payload) { // 可根据需求保留数量最小为0的判断,避免出现负数 return { ...phone, quantity: Math.max(0, phone.quantity - 1) }; } return phone; }); return { ...state, phones: decreasedPhones }; // 必须添加默认分支,未匹配的action直接返回原state default: return state; } }; const Cart = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div className="cart_div"> <h1>Your Bag</h1> {/* 此处替换为遍历state中托管的phones数组 */} {state.phones.map(phone => <PhoneListItem key={phone.id} dispatch={dispatch} {...phone} /> )} </div> ); }; const PhoneListItem = ({ name, price, img, quantity, dispatch, id}) => { return ( <div className="phone_row"> <img className="phone_img" src={img} alt={name} /> <div className="phone_info_div"> <h4>{name}</h4> <h4 className="price">{price}</h4> </div> <div className="phone_amount_div"> <button className="increase_button" onClick={() => dispatch({ type: "increase", payload: id })}> <Icon icon="akar-icons:chevron-up" /> </button> <p className="phone_amount_para">{quantity}</p> <button className="decrease_button" onClick={() => dispatch({ type: "decrease", payload: id })}> <Icon icon="akar-icons:chevron-down" /> </button> </div> </div> ); };
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

