从列表中删除项目而不渲染React JS

时间:2020-02-29 18:59:19

标签: reactjs

我正在从API中显示表格,因此当我单击以删除它时,应该将其删除

现在它实际上正在删除。但问题是它没有呈现输出

这是该函数的代码

  const delpersonHandler = index => {
    const apiDel = api;
    console.log(index);
    api.splice(index, 1);
    console.log(api);
    setApi({ ...api, apiDel });
  };

这是我打电话给的地方

 <TableCell align="Justify">
   <Button variant="outlined">Edit</Button>
   <Button variant="outlined" onClick={() => delpersonHandler(id)}>
      Delete
   </Button>
 </TableCell>

完整代码可在此处

https://pastebin.com/u7fAefBH

3 个答案:

答案 0 :(得分:2)

假设您正在使用功能组件,useState挂钩将提供两个值,特别是状态的getter和setter,使用参数调用最后一个将设置一个新值并调用render调用。

在示例中,setApi是此setter方法,但是您使用对象作为参数而不是数组来调用它。通过将splice方法与api值一起使用,可以推断出它必须是数组。因此,您需要使用相同的变量类型调用设置器:

const delpersonHandler = index => {
  // Don't apply changes directly, instead clone it and modify it.
  const newApi = api.slice();
  newApi.splice(index, 1);

  // Pass an array instead an object
  setApi(newApi); 
};

答案 1 :(得分:2)

反应状态是不可变的,因此执行api.splice(index, 1);不会成功,因为您直接影响反应状态。

api是一个数组,但是您要在setApi函数中设置一个对象

最简单的方法是

const delpersonHandler = index => {
    let oldApi = [...api] // new array containing api's elements
    oldApi.splice(index,1); 
    setApi(oldApi);
  };

答案 2 :(得分:0)

我通过使用以下代码找到了解决方法

const delpersonHandler = index => {
const apiDel= [...api]; //getting the current state of array using spread operator
apiDel.splice(index, 1);  //deleting based on index
setApi(apiDel);
console.log("state updated", api);
}

[... api]如果没有此行,则无法正常工作