我的reducer函数,如下面的代码所示,被多次调用,导致我的incremention被worng和递增2. 我在strictmode下运行这个,所以我知道它会再次渲染一次以确保安全.但它不应该影响国家/
export const ItemContext = createContext();
export const CartItemContext = createContext();
function reducer(state,action){
if(action.type === "increment-quantity")
{
console.log(state[action.mealIndex][1]);
state[action.mealIndex][1] +=1 ;
}
else if(action.type === "decrement-quantity")
{
}
else if(action.type === "add-meal")
{
state = [...state,[action.meal,1]];
}
return state;
}
function App() {
const [orderedMeals,dispatch] = useReducer(reducer,[]);
const [openModal,setOpenModal] = useState(false);
const [Quantity,setQuantity] = useState(0);
const [isFetching,menu,setFetchedData,error]= useFetch(fetchMeals,[]);
const onAddToCart = (meal) => {
const mealFound = orderedMeals.find((mealPair) => {return mealPair[0] === meal;})
const mealIndex = orderedMeals.indexOf(mealFound);
if(mealFound === undefined)
{
dispatch({type:"add-meal",meal:meal})
}
else
{
dispatch({type:"increment-quantity",mealIndex:mealIndex});
}
setQuantity(Quantity+1);
};
我不知道该怎么解决这个问题,请帮忙,谢谢.