简体   繁体   中英

update value of an object in an array - react hooks

I want to increment the counter value of an item on click, I've tried to find the solution in the docs and I watched tutorials but I can't find the solution.

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

You can try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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