我的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);
  };

我不知道该怎么解决这个问题,请帮忙,谢谢.

推荐答案

Issue

这是由于你的约化函数中状态的直接Mutations .您不应该直接改变状态,因为它可能导致意外的行为.相反,您应该返回一个新状态.

Solution

我正在使用map函数创建一个新数组,其中所需餐食的数量是递增的.它确保返回新状态.

function reducer(state, action) {
  switch (action.type) {
    case "increment-quantity":
      return state.map((item, index) =>
        index === action.mealIndex ? [item[0], item[1] + 1] : item
      );
    case "add-meal":
      return [...state, [action.meal, 1]];
    default:
      return state;
  }
}

Javascript相关问答推荐

拖放仅通过 Select 上传

将状态向下传递给映射的子元素

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

将自定义排序应用于角形数字数组

WebRTC关闭navigator. getUserMedia正确

如何使覆盖div与可水平滚动的父div相关?

如何将Cookie从服务器发送到用户浏览器

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

是什么导致了这种奇怪的水平间距错误(?)当通过JavaScript将列表项元素追加到无序列表时,是否在按钮之间?

映射类型定义,其中值对应于键

400 bad request error posting through node-fetch

Reaction-SWR-无更新组件

MongoDB受困于太多的数据

如何在Java脚本中对数据进行签名,并在PHP中验证签名?

通过跳过某些元素的对象进行映射

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

使用VITE开发服务器处理错误

Reaction-在同一页内滚动导航(下拉菜单)

用内嵌的含selenium的Java脚本抓取网站

与find()方法一起使用时,Mongoose中的$or运算符没有提供所有必需的数据