【发布时间】:2021-12-29 19:32:31
【问题描述】:
我正在尝试使用 reducer 函数来更新状态。我有一个状态变量,phones,它是一个 phone 对象数组。当用户单击一个按钮时,我希望电话对象的数量属性增加。数量确实增加了,但 UI 没有变化。
这是我的代码:
const initialState = {
phones: [...Phones]
};
const reducer = (state, action) => {
if (action.type === "increase") {
const newPhones = state.phones.map(phone => {
if (phone.id === action.payload) {
return { ...phone, quantity: phone.quantity + 1 };
}
return phone;
});
return { ...state, phones: newPhones };
}
};
const Cart = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div className="cart_div">
<h1>Your Bag</h1>
{Phones.map(phone =>
<PhoneListItem
key={phone.id}
dispatch={dispatch}
state={state}
{...phone}
/>
)}
</div>
);
};
const PhoneListItem = ({ name, price, img, quantity, dispatch, id, state}) => {
return (
<div className="phone_row">
<img className="phone_img" src={img} />
<div className="phone_info_div">
<h4>
{name}
</h4>
<h4 className="price">
{price}
</h4>
</div>
<div className="phone_amount_div">
//user clicks on button to increase phone quantity
<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>
);
};
【问题讨论】:
-
在
Cart尝试将{Phones.map(phone =>更改为{state.phones.map(phone => -
哇它现在可以工作了,但是为什么
-
因为
Phones是从组件外部声明或导入的变量并且永远不会更新,而state.phones是从useReducer钩子返回的值,当您调度事件时它实际上会更新.
标签: reactjs react-hooks use-reducer