React error when removing input component

前端 未结 3 436
伪装坚强ぢ
伪装坚强ぢ 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:39

    The problem is that you're using the array index as your key, so React will reuse the first two li elements and drop the last one. Change key={index} to key={filter.id}, and it works as you would expect.

    Update concerning the comment & downvote: I assumed uniqueness on filters in the actual code, given that the field is called id. The CodePen seems more of a stripped down version to show the problem. But if you do actually wish to let each button create multiple text fields, you'd indeed need to add something extra to distinguish the keys (e.g. a counter). This doesn't affect the problem as stated in the question though.

    Looking at the code again, I noticed getInput would be an ideal candidate to extract into a separate (stateless) component, e.g. FilterInput. This fits better with the react model than keeping child renderings in the component state.

提交回复
热议问题