代码之家  ›  专栏  ›  技术社区  ›  Dawn17

使用React钩子更改对象内部的数组

  •  0
  • Dawn17  · 技术社区  · 5 年前

    我有一张表格看起来像,

    const virtual_form = {
        name: 'virtual',
        address_info: [
            {
                name: 'a',
                address: '',
            }
        ]
    }
    

    我使用这个作为钩子的默认状态

    const [virtualForm, setVirtualForm] = useState(virtual_form)
    

    address 字段。

    <div className="input-text-wrapper">
        <TextField
            value={virtualForm.address_info.address}
            name="address"
            onChange={(e) => handleAccessInfoChange(e, 'virtual')} />
    </div>
    

    就像上面说的。

    然而,在我的 handleAccessInfoChange ,

    const handleAccessInfoChange = (e, type) => {
        console.log(e.target.name, e.target.value, type)
        switch (type) {
            case 'virtual':
                setVirtualForm({...virtualForm, address_info[0]: [...virtualForm.address_info, address: value] })
        }
    }
    

    virtualForm . 上面写着 'address' is not defined no-undef .

    地址

    0 回复  |  直到 5 年前
        1
  •  2
  •   Brian Thompson    5 年前

    你在用 address name 作为数组,但不能使用此语法指定数组 [address: value] . 它在寻找一个名为 不把它当作钥匙。

    相反,映射到它上面并在正确的索引处修改对象。我不知道是哪个索引,所以我假设 0 在问题中:

    setVirtualForm({
      ...virtualForm, 
      address_info: virtualForm.address_info.map((info, i) => {
        if (i == 0) {
          return {
            ...info,
            address: value
          }
        }
        return info
      }
    })