简体   繁体   English

更新数组中 object 的值 - 反应钩子

[英]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 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 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;
      })
    );
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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