React Native-更新数组中对象的属性

时间:2020-03-19 15:54:06

标签: javascript arrays react-native

具有一个对象数组,并且想使用increaseQuantity()函数仅更新对象的stock属性。我该怎么办?

    increaseQuantity = (id) => {
    let newData = this.state.data.map(obj => {
        if (obj.id === id) {
            //Block of Code
        }
        return obj
    })
    this.setState({ newData })

    console.log(newData)
}

样本数据如下:

    const Items = [
{ id: '0', text: 'Alvaro Beer', stock: 500 },
{ id: '1', text: 'Malta Guinnesse', stock: 200 }

渲染元素:

    <FlatList
                        data={Items}
                        renderItem={({ item }) => (
                            <Products
                                id={item.id}
                                text={item.text}
                                price={item.price}
                                stock={item.stock}
                                onSwipeIncrease={() => this.increaseQuantity()}
                                onSwipeDecrease={() => console.log('Sub')}
                                onSwipeAddToCart={() => console.log('Cart')}
                            />
                        )}
                        keyExtractor={item => item.id}
                    />

1 个答案:

答案 0 :(得分:0)

检查这个简单的解决方案

increaseQuantity = id => {
  let updateItems = [...this.state.items];
  // get the index according to id
  let index = this.state.items.findIndex(obj => obj.id == id);
  // check whether passed id exits in the items
  if (!!index) {
    // suppose you want to change stock value to 2000
    updateItems[index].stock = 2000;
    this.setState({
      items: updateItems
    });
  }
};

为此,您的state应该喜欢

state = {
  items: [
    { id: "0", text: "Alvaro Beer", stock: 500 },
    { id: "1", text: "Malta Guinnesse", stock: 200 }
  ]
}

希望这对您有所帮助。放心怀疑。