reactjs从render方法中的数组中删除元素

时间:2018-10-17 00:40:06

标签: reactjs

我的状态为public static void main(String[] args) { System.out.println("main"); // this is only here so MyGuiceModule gets called, otherwise // it will be ignored. this seems to be the only way I can see // to configure Guice. note that the returned Injector is not used. Injector injector = Guice.createInjector(new MyGuiceModule()); TheTest t = new TheTest(); // crashes here with Exception in thread "main" java.lang.NullPointerException t.doit(); } 的数组。假设这是我处于状态的数组:columnToFilterOut

我还有另一个状态为columnToFilterOut = ["first_col", "second_col", "third_col"]的数组,其中包含字典列表,其中有一个名为id的键对应于columnToFilterOut中的值。这是rows的示例:

rows

如您所见,其中还有一个额外的元素。额外的值是id =“ fourth_col”的值。我想删除所有元素以确保两个数组匹配。

这是我的删除功能:

rows: [
    {
      id: "first_col",
      numeric: false,
      disablePadding: true,
      label: "1"
    },
    {
      id: "second_col",
      numeric: true,
      disablePadding: false,
      label: "2"
    },
    {
      id: "third_col",
      numeric: true,
      disablePadding: false,
      label: "3"
    },
    {
      id: "fourth_col",
      numeric: true,
      disablePadding: false,
      label: "4"
    }
]

所以我传入一个ID,它应该删除具有给定ID的值。在我的渲染函数中,我像这样使用它:

removeFromRowsById(id) {
    console.log("IN REMOVE FUNCTION");
    const filteredValues = this.state.rows.filter((_, i) => i["id"] !== id);
    this.setState({ rows: filteredValues });

}

这不起作用。行数组中的值永远不会删除。我打印以确保。我还注意到,我在Object.keys(rows).map( (key, index) => !(columnToFilterOut.indexOf(rows[index]["id"]) > -1) //meaning the value doesn't exist inside of columnToFilterOut ? this.removeFromRowsById.bind(this, rows[index]["id"]) : console.log("Not deleting") ); 内的print语句从未登录到控制台,就像从未真正调用过该函数一样。任何帮助都很棒。谢谢!

2 个答案:

答案 0 :(得分:1)

尝试更改您的this.state.rows.filter,如下所示。看看是否有效

removeFromRowsById(id) {
   console.log("IN REMOVE FUNCTION");
   // 1. the original code should be === not !==, because you want to delete when the id matches.
   // 2. the "i" should be on first parameter not second
   const filteredValues = this.state.rows.filter((i, _) => i["id"] === id); 
   this.setState({ rows: filteredValues });
}

答案 1 :(得分:0)

我将removeFromRowsById更改如下:

removeFromRowsById = index => {
  console.log("IN REMOVE FUNCTION");
  const newList = [...this.state.rows1];
  newList.splice(index, 1);

  this.setState(state => ({
    rows1: newList
  }));
};

我会定期在render函数中调用它(没有绑定)。我认为您需要使用箭头功能修复该问题,并且在@ vdj4y说的是正确的情况下,我修改了它从列表中删除的方式