更新数组元素

Update array elements

我正在尝试做一些类似于购物车的事情,最初有一系列的产品,我用一组对象加载它们。

products = [
        {
            id: 1,
            name: "Product1",
        },
        {
            id: 2,
            name: "Product2",
        },
        {
            id: 3,
            name: "Product",
        },

];

我展示的产品列表是这样的:

<div class="col-md-12 row grid">
    {#each products as product}
        <div class="card mt-2 g-col-3">
            <div class="row">
                <div class="col-md-8">
                    <div class="card-body">
                        <h5>{product.name}</h5>
                        <button
                            on:click={addProduct(product.id)}
                            class="btn btn-primary">Add Product
                        </button>
                        { "0 products"}
                    </div>
                </div>
            </div>
      </div>
    {/each}
</div>

然后通过函数 addProduct() 我用产品 ID 和该产品的单位数更新数组 库存

let inventory =[];
const addProduct = id =>{
        
        let qty = 0;
        if(inventory.find(element => element.id === id))
        {
            qty = inventory.find(element => element.id === id).qty
            inventory=inventory.filter(element => element.id !== id)
            inventory.push({id:id,qty:qty+1});

        }
        else{       
        inventory.push({id:id,qty:1});
        }
        
    }

我不知道如何设置它的地方是在每个产品中,它现在显示 {“0 个产品”},当用户添加每个产品时动态更新它

非常感谢!

我了解到 { "0 products"} 您想显示库存中的物品数量。您可以将其替换为

{inventory.find(element => element.id === product.id)?.qty ?? 0} products

Optional chaining (?.) and Nullish coalescing operator (??) 使用

除了您希望在进行编辑(如推送项目)后 assign inventory to itself 以触发 re-render 之外,addProduct() 中存在逻辑问题。如果已经有一个元素,你不想推另一个,而是编辑现有的,这给了

function addProduct(id) {
        const element = inventory.find(element => element.id === id)
        if(element) {
            element.qty += 1
            inventory = inventory
        }
        else{       
            inventory.push({id:id,qty:1});
            inventory = inventory
        }
    }

虽然这可行 - 请参阅 this REPL - I would consider making inventory an object instead of an array, because it was a bit 'quicker' to check for entries and edit them, compare this REPL(条目总是可以使用 Object.entries/.keys/.values(inventory) 轻松迭代)

<script>
    import {products} from './products'

    let inventory = {}

    function addProduct(id) {
        const entry = inventory[id]
        if(entry) {
            entry.qty += 1
            inventory = inventory
        }
        else{       
            inventory[id] = {qty:1}
            inventory = inventory
        }
    }
</script>

<div>
    {#each products as product} 
    <h5>{product.name}</h5>
    <button on:click={() => addProduct(product.id)}>
        Add Product
    </button>
    {inventory[product.id]?.qty ?? 0} products
    {/each}
</div>