反应从嵌套列表中删除项目

时间:2019-05-15 20:30:37

标签: reactjs

我有一个列表项:

  • 选择敷料
    1. 多余的肉[x]
    2. 额外土豆[x]
  • 选择蛋白质
    1. 暗黑破坏神[x]

每个项目都有一个删除按钮,我想在单击“ x”按钮时删除选定的项目,这是我的代码:

状态数组:

extraOptionsCategory: [
        {
          "name": "Select Dressing",
          "id": 1,
          extraOptions: [{
            "name": "Extra Meat",
            "price": 4
          },
          {
            "name": "Extra Potato",
            "price": 2
          }]
        },
        {
          "name": "Select Protein",
          "id": 2,
          extraOptions: [{
            "name": "Queso Diablo",
            "price": 2
          }]
        }
      ]

渲染代码:

                {this.state.extraOptionsCategory.map((a, index) => {

                  return (
                    <div key={index}>

                      {a.name}

                      {a.extraOptions.map((b, idx) => {
                        return (
                          <div key={idx}>

                            {b.name}

                            <button onClick={this.removeItem.bind(this, idx)}>x</button>
                          </div>
                        )
                      })}

                    </div>
                  )
                })}
              </div>

并删除功能:

removeItem = (idx) => {
    console.log(idx);

    ???
  }

1 个答案:

答案 0 :(得分:1)

我认为最好为每个extraOptionsCategory和extraOptions设置一个唯一的ID,而不要依赖于ID作为映射的索引。

原因是您正在尝试删除某些东西,而您想通过它的唯一ID来做到这一点,而不是因为它在数组中的位置与要删除的选项完全无关。

使用该唯一ID,并将其设置为按钮的attribute值。

将该值传递给按钮上的removeItem函数。

如果您正在使用map的索引,并且数组发生突变,则可能不会删除您认为要引用的内容。


extraOptionsCategory: [
        {
          "name": "Select Dressing",
          "id": 1,
          extraOptions: [{
            "name": "Extra Meat",
            "price": 4,
            "id": 1a
          }]
        }]

...

<button onClick={(e) => {this.removeItem.bind(this, e.value)}} value={b.id}>x</button>
相关问题