SoFunction
Updated on 2025-03-10

Addition and delete list methods involved in react

React involves addition, delete list

One of the functions of the project is that it requires the list composed of multiple Inputs to be added and deleted.

The solution I thought at the beginning was to use index directly. This can be added, but if you cannot delete it, the list will be incorrect. Even if you delete one in the middle, it is always the last one to be deleted. The reason is that index-1 will only delete the last one, and the list will be refreshed after re-rendering.

If it is just added but not filled in the content, it doesn’t matter if it is deleted, but if it is added and then deleted, there will be a problem.

The solution is to use a unique identifier, that is, the id, which means that the front-end generates the id itself, and you will not be confused if you delete it according to the id.

In this project, since new creation and editing are the same page, and after entering this page, we will distinguish whether it is new creation or editing based on whether there is xxId, because two different interfaces will be requested to obtain data. So, on the return value requested from the interface, a unique identifier is added, that is, selfId. I'm operating on the result obtained after dispatch.

as follows:

const dealListData = (result) => {
    // ('listR', result);
    if (===0) {
        ({
            selfId:1
        });
    } else {
        ((item, index) => {
             = String(index + 1);
            return item;
        });
    }
    // (result);
    return result;
};

New functions

List refers to a block composed of several Inputs, which are to be added and deleted.

handleAdd = () => {
     let selfId = Number([-1].selfId) + 1;
     // ([-1].selfId +1);
     ((err, value) => {
        if (!err) {
            ({
                selfId:selfId
        });
        ();
      }
   });
}

Deleted functions

handleDeleteItem = (i, selfId) => {
    ({ list: (item =>  !== selfId) }, () => {
          // ('delete', );
          ();
    });
}

Delete according to selfId

Because list is a child component that I repackaged again, and the value must be reflected to the parent component in real time, all needs to be updated in real time through events. There is no problem with deleting and adding in this way.

Summarize

If you cannot add or delete new ones based on the index index, it will be confused. A unique identifier is required to be updated.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.