【问题标题】:How to update specific value in a array of JSON values in React, can anyone please explain this如何在 React 中更新 JSON 值数组中的特定值,谁能解释一下
【发布时间】:2020-12-04 07:17:48
【问题描述】:

没有使用 setState 更新 JSON 状态

1.我想更改 JSON 中的特定数量值,为此我写了一个 标记的 IncrementHandler 方法并实现了该功能,但它没有更新我的 主要状态

2.我在函数内部实现了setState方法来更新状态。

import React, { Component } from 'react';

export default class App extends Component {
  state = {
    value: 0,
    students: [
      {
        item: 'salad',
        qty: 2,
        department: 'Information Technology',
        rollno: '123'
      },
      {
        item: 'cheese',
        qty: 2,
        department: 'Computer Engineering',
        rollno: '456'
      },
      {
        item: 'meat',
        qty: 2,
        department: 'Information Technology',
        rollno: '789'
      }
    ]
  };

  render() {
    const IncrementHandler = (type) => {
      if (type === 'salad') {
        this.setState((prevState) => ({
          qty: this.state.students[0].qty + 1
        }));
      }
    };

    return (
      <div>
        <div>
          <div>
            <table border="2">
              <tbody>
                <tr>
                  <th>Item</th>
                  <th>Quantity</th>
                  <th>Button</th>
                </tr>
                {this.state.students.map((item, i) => (
                  <tr key={i}>
                    <td>{item.item}</td>
                    <td>{item.qty}</td>
                    <td onClick={() => IncrementHandler(item.item)}>click</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }
}

【问题讨论】:

  • @Naren 我更新了代码请看

标签: javascript reactjs


【解决方案1】:

问题

您没有更新 student 数组中的嵌套状态。您正在生成一个新的根状态密钥 qty。

this.setState(prevState => ({
  qty : this.state.students[0].qty + 1
}))

解决方案

浅复制student 数组以创建新的数组引用,并浅复制要更新的元素在数组中。关于在 react 中更新嵌套状态的一般注意事项,您需要对正在更新的任何对象进行浅拷贝,因为 React 使用浅对象相等性来协调差异。

const IncrementHandler = item => {
  this.setState(prevState => ({
    students: prevState.students.map(student =>
      student.item === item
        ? {
            ...student,
            qty: student.qty + 1,
          }
        : student,
    ),
  }));
};

注意:您可能还应该在渲染函数之外声明此回调。它仍然可以在渲染方法中定义,但是这违反了惯例。

【讨论】:

  • 非常感谢!!!!德鲁里斯,我学到了一件事???!!
  • @LalithAditya 太棒了!如果这解决了您的问题,那么请将答案标记为已接受,如果解释有帮助,请点赞。干杯。
猜你喜欢
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 2017-04-07
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多