简体   繁体   English

如何删除多个数组项

[英]How can I delete Multiple array items

I'm using React js.我正在使用反应 js。 I want to add an option to delete multiple items.我想添加一个选项来删除多个项目。 but after deleting each item, page refreshes the props and not delete remaining items.但是在删除每个项目后,页面会刷新道具而不是删除剩余的项目。

How can I delete Multiple items?如何删除多个项目?

const onDeleteAll = arr => {
        
    arr.forEach(element => {
      const formData = {
        id:element
      }

      props.onDeleteSubmit(formData, function(){ // pass id to delete func
        console.log('deleted')
      })
    });
  }
  useEffect(() => {
    props.getPriceType(); // fetching data
  }, []);

reducer:减速器:

case DELETE_PRICE_TYPE_SUCCESS_ACTION:
          const myDeletedArray = draft.list;
          const objDeletedIndex = myDeletedArray.filter(obj => obj.id !== action.payload._id);
          draft.list = objDeletedIndex; //update data
          break;

 var id = 23; var list = [{ id: 23, value: "JOHN" }, { id: 23, value: "JADE" }, { id: 24, value: "JADE" }, { id: 25, value: "JAMES" }]; var indexes = []; const templist = list.filter((item, ind) => { return item.id;== id }); list = templist. console;log(list);

First get the list of indexes which matches the items in the array to be deleted.首先获取与要删除的数组中的项目匹配的索引列表。 Traverse the above list and delete the items from each array by splice operator.遍历上面的列表,并通过拼接操作从每个数组中删除项目。

I think the problem is that you have multiple items to delete, but you trigger a delete action for only 1 at a time.我认为问题在于您有多个要删除的项目,但您一次只能触发 1 个删除操作。 You need to collect all the ids to delete in a list, and send that list to the action, and in reducer just filter that ids.您需要收集要在列表中删除的所有 id,并将该列表发送到操作,并且在 reducer 中只需过滤该 id。

const onDeleteAll = arr => {

  //this just to follow your current shape of things
  //ideally you don't want to do that, just pass arr to the onDeleteSubmit

  const formData = arr.map(element => ({
      id:element
  }));

  props.onDeleteSubmit(formData, function(){
      console.log('deleted')
  })  
  
}
useEffect(() => {
  props.getPriceType(); // fetching data
}, []);

reducer:减速器:

case DELETE_PRICE_TYPE_SUCCESS_ACTION:
          const myDeletedArray = draft.list;
          const objDeletedIndex = myDeletedArray.filter(obj => 
            !action.payload.find(itemToDelete=>itemToDelete._id===obj.id)
          );
          draft.list = objDeletedIndex; //update data
          break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM