Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新状态->;对象->;阵列->;对象_Javascript_Arrays_Reactjs_Object_Setstate - Fatal编程技术网

Javascript 更新状态->;对象->;阵列->;对象

Javascript 更新状态->;对象->;阵列->;对象,javascript,arrays,reactjs,object,setstate,Javascript,Arrays,Reactjs,Object,Setstate,在深度嵌套的setState函数中迷失方向 我试图做的是将一个对象添加到我的组件状态中的一个对象内的数组中。我已经成功地这样做了,但是我正在尝试这样做,如果该对象已经存在,函数将更新数量。我不确定我做错了什么 状态 this.state = { products : [ { productId: 1, productImage: 'tee1', productName: 'The Road Is Ho

在深度嵌套的setState函数中迷失方向

我试图做的是将一个对象添加到我的组件状态中的一个对象内的数组中。我已经成功地这样做了,但是我正在尝试这样做,如果该对象已经存在,函数将更新数量。我不确定我做错了什么

状态

this.state = {
    products : [
        {
            productId: 1,
            productImage: 'tee1',
            productName: 'The Road Is Home Tee',
            productPrice: 25
        },
        {
            productId: 2,
            productImage: 'shorts1',
            productName: 'Striped Swim Shorts',
            productPrice: 50
        },
        {
            productId: 3,
            productImage: 'tee2',
            productName: 'Gray Long Sleeve',
            productPrice: 100
        },
        {
            productId: 4,
            productImage: 'hat1',
            productName: 'American Snapback',
            productPrice: 25
        },
        {
            productId: 5,
            productImage: 'shorts2',
            productName: 'American Shorts',
            productPrice: 50
        },
        {
            productId: 6,
            productImage: 'hat2',
            productName: 'Flex Fit Hat',
            productPrice: 100
        }
    ],
    cartData : {
        items: [],
        total: 0
    }
}
addToCart()

addToCart=(产品ID、大小、数量)=>{
for(设i=0;i{
const items=prevState.cartData.items.map(item=>{
如果(i==(item.productId-1)){
退货项目.产品数量+数量;
}
})
返回{
项目,
}
})
}否则{
this.setState(prevState=>({
cartData:{
…prevState.cartData,
items:[…prevState.cartData.items,{productData:this.state.products[productId-1],productSize:size,productQuantity:quantity}]
}
}))
}
}
}   
编辑***********

新代码更有条理,我在开始时实现了一个IF语句,在我循环项目之前检查购物车是否为空。还修复了一些小问题并添加了一些评论,但仍然没有得到我想要的结果

addToCart = (productId, size, quantity) => {
        // IF CART IS EMPTY (CANT USE FOR LOOP)
        if ( this.state.cartData.items.length === 0 ) {
            this.setState(prevState => ({
                cartData: {
                    ...prevState.cartData,
                    items: [...prevState.cartData.items, { productData: this.state.products[productId - 1], productSize: size, productQuantity: quantity }]
                }
            }))
        }
        // IF CART IS NOT EMPTY
        else {
            // LOOP THROUGH EACH ITEM
            for( let i=0; i < this.state.cartData.items.length; i++ ) {
                // IF PRODUCT EXISTS
                if (productId === this.state.cartData.items[i].productData.productId) {
                    // SET STATE (RETURNS A FUNCTION)
                    this.setState(prevState => {
                        // MAP THROUGH EACH ITEM
                        const items = prevState.cartData.items.map(item => {
                            // IF THE PRODUCT IDS MATCH
                            if(i === (item.productData.productId -1)) {
                                // RETURN AN OBJECT WITH SAME ITEM PROPERTIES
                                // ADJUST QUANTITY
                                return {
                                    ...item,
                                    productQuantity: item.productQuantity + quantity,
                                }
                            }
                            // RETURN UNAFFECTED ITEMS AS WELL
                            else {
                                return item
                            }


                        })

                        // RETURN OUR ITEMS TO SET STATE
                        return {
                            items,
                        }
                    })
                }
                // IF PRODUCT DOES NOT EXIST
                else {
                    this.setState(prevState => ({
                        cartData: {
                            ...prevState.cartData,
                            items: [...prevState.cartData.items, { productData: this.state.products[productId - 1], productSize: size, productQuantity: quantity }]
                        }
                    }))
                }
            }
        }
    }

addToCart=(产品ID、大小、数量)=>{
//如果购物车为空(不能用于循环)
if(this.state.cartData.items.length==0){
this.setState(prevState=>({
cartData:{
…prevState.cartData,
items:[…prevState.cartData.items,{productData:this.state.products[productId-1],productSize:size,productQuantity:quantity}]
}
}))
}
//如果购物车不是空的
否则{
//循环浏览每个项目
for(设i=0;i{
//映射每个项目
const items=prevState.cartData.items.map(item=>{
//如果产品ID匹配
如果(i==(item.productData.productId-1)){
//返回具有相同项属性的对象
//调整数量
返回{
…项目,
productQuantity:item.productQuantity+数量,
}
}
//返回未受影响的项目以及
否则{
退货项目
}
})
//将项目返回到设置状态
返回{
项目,
}
})
}
//如果产品不存在
否则{
this.setState(prevState=>({
cartData:{
…prevState.cartData,
items:[…prevState.cartData.items,{productData:this.state.products[productId-1],productSize:size,productQuantity:quantity}]
}
}))
}
}
}
}
到目前为止,我的应用程序将正确添加第一个产品。然后在那之后我就开始有问题了。当我尝试添加另一个具有相同产品ID的产品时,它不仅会增加创建整个其他对象的数量

sooo在这里迷路了,请帮忙

p、 美国。
在沙盒内部使用localhost时没有得到错误,因此这里不是一个真正的选项

我没有尝试运行代码(如果您提供codesandbox或其他东西就可以了),但这应该会有所帮助

addToCart = (productId, size, quantity) => {
    for( let i=0; i < this.state.cartData.items.length; i++ ) {
        if (productId === this.state.cartData.items[i].productData.productId) {
            this.setState(prevState => {
                const items = prevState.cartData.items.map(item => {


                    if(i === (item.productId -1)) {
                        // returns a copy of the known item with updated quantity
                        return {
                            ...item,
                            productQuantity: item.productQuantity + quantity,
                        };
                    } else {
                        return item // you need to return items that are not modified too
                    }


                })

                return {
                    items,
                }
            })
        } else {
            this.setState(prevState => ({
                cartData: {
                    ...prevState.cartData,
                    items: [...prevState.cartData.items, { productData: this.state.products[productId - 1], productSize: size, productQuantity: quantity }]
                }
            }))
        }
    }
}   
addToCart=(产品ID、大小、数量)=>{
for(设i=0;i{
const items=prevState.cartData.items.map(item=>{
如果(i==(item.productId-1)){
//返回具有更新数量的已知项目的副本
返回{
…项目,
productQuantity:item.productQuantity+数量,
};
}否则{
return item//您需要返回未修改的项目
}
})
返回{
项目,
}
})
}否则{
this.setState(prevState=>({
cartData:{
…prevState.cartData,
items:[…prevState.cartData.items,{productData:this.state.products[productId-1],productSize:size,productQuantity:quantity}]
}
}))
}
}
}   

它可以工作。我希望它能帮助你。(对更具组织性的代码进行了一些更改):

]


这对我来说是有道理的,但我只是尝试了一下,发现和以前一样的问题。当我console.log()我的cartData是空的…对此非常困惑。首先,为什么要将这些类函数设为常量?我犯了很多错误,试试看
addToCart = (productId, size, quantity) => {
    for( let i=0; i < this.state.cartData.items.length; i++ ) {
        if (productId === this.state.cartData.items[i].productData.productId) {
            this.setState(prevState => {
                const items = prevState.cartData.items.map(item => {


                    if(i === (item.productId -1)) {
                        // returns a copy of the known item with updated quantity
                        return {
                            ...item,
                            productQuantity: item.productQuantity + quantity,
                        };
                    } else {
                        return item // you need to return items that are not modified too
                    }


                })

                return {
                    items,
                }
            })
        } else {
            this.setState(prevState => ({
                cartData: {
                    ...prevState.cartData,
                    items: [...prevState.cartData.items, { productData: this.state.products[productId - 1], productSize: size, productQuantity: quantity }]
                }
            }))
        }
    }
}   
const products = [
{
  productId: 1,
  productImage: 'tee1',
  productName: 'The Road Is Home Tee',
  productPrice: 25
},
{
  productId: 2,
  productImage: 'shorts1',
  productName: 'Striped Swim Shorts',
  productPrice: 50
},
{
  productId: 3,
  productImage: 'tee2',
  productName: 'Gray Long Sleeve',
  productPrice: 100
},
{
  productId: 4,
  productImage: 'hat1',
  productName: 'American Snapback',
  productPrice: 25
},
{
  productId: 5,
  productImage: 'shorts2',
  productName: 'American Shorts',
  productPrice: 50
},
{
  productId: 6,
  productImage: 'hat2',
  productName: 'Flex Fit Hat',
  productPrice: 100
}
const [cart, setCart] = useState({
items: [],
total: 0
})

const isProductExist= productId =>
  cart.items.find(product => product.productId == productId)

addToCart = (productId, size, quantity) => {
  if (isProductExist(productId)) {
  setCart(prevState => ({
    ...prevState,
    items: cart.items.map(item => {
      if (item.productId == productId) item.productQuantity += quantity
      item.productQuantity
      return item
    })
  }))
} else {
  setCart(prevState => ({
    ...prevState,
    items: [
      ...prevState.items,
      {
        productId: products[productId - 1].productId,
        productSize: size,
        productQuantity: quantity
      }
    ]
  }))
 }
}