簡體   English   中英

更新數組中 object 的值 - 反應鈎子

[英]update value of an object in an array - react hooks

我想在點擊時增加一個項目的計數器值,我試圖在文檔中找到解決方案,我觀看了教程,但我找不到解決方案。

FruitCounter.js

import { Fragment, useState } from "react"
import Fruit from "./Fruit"

const data = [
    { id: 1, name: "🍋", counter: 0 },
    { id: 2, name: "🍒", counter: 0 },
]

const FruitCounter = () => {
    const [fruits, setFruits] = useState(data)

    const clickHandler = (fruit) => {
       // Increment 'counter value of clicked item by 1'
    }

    return (
        <Fragment>
            {fruits.map((fruit) => {
                return (
                    <Fruit
                        key={fruit.id}
                        {...fruit}
                        clickHandler={() => clickHandler(fruit)}
                    />
                )
            })}
        </Fragment>
    )
}

export default FruitCounter

Fruit.js

import React from "react"

const Fruit = ({ counter, name, clickHandler }) => {
    return (
        <button type="button" className="fruit" onClick={clickHandler}>
            <p>{counter}</p>
            <h2>{name}</h2>
        </button>
    )
}

export default Fruit

你可以試試這個

  const clickHandler = (fruit) => {
    setFruits(
      fruits.map((x) => {
        if (x.id === fruit.id)
          return {
            ...x,
            counter: x.counter + 1,
          };
        return x;
      })
    );
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM