【问题标题】:How can I manipulate a 2D array in React?如何在 React 中操作 2D 数组?
【发布时间】:2019-07-26 12:28:34
【问题描述】:

我试图将设备列表保存在数组中。 我需要为每个设备添加数量,所以我必须将一维转换为二维

如何将状态数组中的此声明更改为 2D?

this.state = {
        equipments: [{
            number: ''
        },{
            number: ''
        }]};

以及如何设置?

handleSubmit(event) {
    const orderData = {
        equipments: this.state.equipments.map(equipment => {
            return {equipemnt: equipment.number} 
        })    
    };
    createOrder(orderData);
}


validateEquipment = (equipmentNumber) => {
    if(equipmentNumber.length === 0) {
        return {
            validateStatus: 'error',
            errorMsg: 'Please enter a choice!'
        }
    } else if (equipmentNumber.length > 50) {
        return {
            validateStatus: 'error',
            errorMsg: `Choice is too long (Maximum 50 characters allowed)`
        }    
    } else {
        return {
            validateStatus: 'success',
            errorMsg: null
        }
    }
}

handleEquipmentChange(event, index) {
    const equipments = this.state.equipments.slice();
    const value = event.target.value;

    equipments[index] = {
        number: value,
        ...this.validateEquipment(value)
    }

    this.setState({
        equipments: equipments
    });
}

【问题讨论】:

  • 二维数组是数组的数组。你的状态应该是equipments: [[// 1 array]],[// 2 array]]
  • 我使用了这种语法,但在我的情况下它不起作用
  • 你想使用什么样的二维数组?您能否在您的问题中也添加该结构
  • 如果设备中的每个对象都代表设备,那么我认为数量应该是每个对象中的另一个关键。所以你的设备数组会像 [{ number; "", 数量:0}]
  • 是的,这就是我需要的,我会试试的

标签: arrays reactjs state


【解决方案1】:

如果你使用对象而不是数组会更容易

this.state = {
  equipments: {
    eq1: { qty: 0 },
    eq2: { qty: 0 }
  }
}

添加/更新新设备很简单:

addOrUpdateQty(id, qty) {
  this.setState({ equipments: {...this.state.equipments, [id]: { qty }} })
}

【讨论】:

  • 谢谢,如果我使用这种方式,我不能使用 foreach 来阅读所有这些吗?我该怎么办?
  • 你可以使用类似的东西,``` Object.values(this.state.equipments).map() ``
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 2014-03-11
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多