【问题标题】:update data with useState in React js在 React js 中使用 useState 更新数据
【发布时间】:2022-12-02 20:23:52
【问题描述】:

I am new to react. I have faced one issue and not able to solve it. I am looking for your help. I have an array which I have listed below. All data are looped and displayed in the view. From my current array, I want to update the count of dietry array[] which is inside the fruits array.

This is my useState

const [foods, setFood] = useState(fruits)

if I console.log(foods) it gives data as below.

fruits: [
    {
        id: 1,
        name: \'Banana\',
        family: \'abc\',
        price: 2.99,
        isEnabled: true,
        dietary: [
            {
                id:1,
                disabled: false,
                group: null,
                selected: false,
                text: \'N/A\',
                value: \'858090000\',
                count:0
            },
            {  
                id:2,
                disabled: true,
                group: null,
                selected: true,
                text: \'N/A\',
                value: \'80000\',
                count:0
            },
        }

This data are looped in a view page and there is onClick handleIncrement method which should increment the count of dietary array of index 0 or index1 etc whichever index sent from handleIncremnt() method. This is my method

const handleIncrementCount = (dietary_index) => {
    setFood(foods =>
        foods.map((food,index) =>
         dietary_index === food[index] ? {...food, qty:food.count+1}:food
        )
    );
}

I am not able to increase the count, in my view page counts are 0 even if i click the increment button.It shows some error within map

Any help is highly appreciated

I ma looking for a solutions

  • should it be dietary_id == index ? ... ?
  • yes, it is an index. Thanks

标签: javascript reactjs


【解决方案1】:
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多