1 回答
TA贡献1851条经验 获得超5个赞
useReducer仅在第一次渲染时使用initialState(在 axios 完成之前),在所有后续的重新渲染中,它只会从内存单元返回状态。useReducer你想要做的是在顶部打电话
const [countState, dispatch] = useReducer(counterReducer, {products: []});
然后打电话dispatch给你getProds
const getProds = () => {
axios.get(`API`).then((res) => {
const data = res.data;
setProds(data.products);
dispatch({ type: "PRODUCTS_FETCHED", payload: data.products});
});
};
并在你的减速器中添加根据大小写来设置状态。
export const counterReducer = (state, action) => {
switch (action.type) {
case "increment":
return {
...state,
products: state.products.map((product) =>
product.id === action.id
? { ...product, count: product.count + 1 }
: product
),
};
case "decrement":
return {
...state,
products: state.products.map((product) =>
product.id === action.id
? {
...product,
count: product.count !== 1 ? product.count - 1 : 1,
}
: product
),
};
case "PRODUCTS_FETCHED":
return {
...state,
products: action.payload
};
default:
return state;
}
};
添加回答
举报