React error when removing input component

前端 未结 3 441
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 08:27

I am not sure if it´s a react issue or not but I am struggling a lot with this issue. I tried to create just a simple example to post out of my project:

https://code

3条回答
  •  不思量自难忘°
    2021-01-16 08:30

    Edit: Please avoid using your ids as keys as the other answers suggest if multiple of the same elements can be added as your initial example suggests because keys need to be unique and this way they can (and will) be repeated!


    Your problem lies in the fact that you are using the key attribute wrongly. React expects your components to have constant keys, so it can decide when and which ones it needs to update.

    If you are modifying an array, the keys of the objects are changing, and the element that had the key '1' before the removal is gone afterwards and the component that previously had key '2' becomes the one with key '1' and so forth.

    The React documentation advises against using the index as key as well:
    "We don’t recommend using indexes for keys if the items can reorder"

    To avoid this you should use some sort of unique key generation and store each components key in it's own object, for example like this:

    In the constructor:

    this.nextKey = 0
    

    When adding a new component:

    tempArr.push({comp: comp, id: e.target.id, key: this.nextKey++});
    

    In the render function:

    return 
  • {filter.comp}
  • I modified your example to include these lines, you can find it here: https://codepen.io/Isti115/pen/MEmMZP?editors=1111


    Also, some other tips:

    • When creating an object that has a key with a value assigned from a variable with the same name, you can shorten it so that this: {comp: comp, id: e.target.id}
      becomes this: {comp, id: e.target.id}.

    • If you need something more robust, you could use a separate unique key generator like this:
      Create GUID / UUID in JavaScript?
      or this:
      https://gist.github.com/gordonbrander/2230317


    ps.: The switch statement you are using is completely useless right now. What have you tried to accomplish with it?

提交回复
热议问题