简体   繁体   English

为什么我的 foreach 和 map 返回未定义

[英]Why is my foreach and map return undefined

I have a packet system where you can have products in a packet.我有一个数据包系统,您可以在其中将产品放在一个数据包中。

So if anyone buy a packet I add this in shopping cart, if he buy it again then I check if the packet id is the same and if the products in packet have the same size and color if yes then I add amount + 1.所以如果有人买了一个包,我把这个添加到购物车中,如果他再次购买,我会检查包 id 是否相同,如果包中的产品具有相同的尺寸和颜色,如果是,则我添加金额 + 1。

The problem is, I got undefined.问题是,我没有定义。

I console log all statements and its logging, I get the values in console log and the statements but he is returning undefined i dont know why...我控制台记录所有语句及其日志记录,我在控制台日志和语句中获取值,但他返回未定义我不知道为什么......

        action.payload.packet?.products.forEach((product => {

         return state.cart.map((el => {
          if(el.packet?.id === action.payload.packet?.id) {
            return {
              ...el,
              product: el.packet?.products.map((state_p => {
                if(product.id === state_p.id) {
                  return {
                    ...state_p,
                    selectedOption: state_p.selectedOption.map((so => {
                      if(so.color === product.selectedOption[0].color && so.size === product.selectedOption[0].size) {
                        console.log('HII333')
                        return {
                          ...so,
                          amount: so.amount + 1
                        }
                      } else {
                        return {
                          ...so
                        }
                      }
                    }))
                  }
                } else {
                  return {
                    ...state_p
                  }
                }
              }))
            }
          } else {
            return {
              ...el
            }
          }
          }));
        }));

did I miss a return statement ?我错过了退货声明吗?

ForEach method works in such way in which it doesn't return anything while it works. ForEach 方法的工作方式是在工作时不返回任何内容。 So even if you add return statement in your forEach, it wouldn't return anything.因此,即使您在 forEach 中添加 return 语句,它也不会返回任何内容。 In your case you can change forEach to map method which returns new array在您的情况下,您可以将 forEach 更改为返回新数组的 map 方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM