A
A
Alexey2020-08-21 15:38:48
React
Alexey, 2020-08-21 15:38:48

Why does the method work incorrectly with adding unique keys?

Created a card with the ability to add tasks. When adding tasks, the method starts adding them incorrectly (duplicates them), and with each addition more and more.
Moreover, if in the renderTasks method in return

return (
          <p className="task"  key={new_current_id} >{item}</p>
        )


remove the addition of an element with the key identifier, then

return (
          <p className="task">{item}</p>
        )


then everything starts to be added correctly (but only the react asks that the elements still have individual keys), but I can’t understand why the elements added with the keys start to be duplicated.

Here is the link to the codepen https://codepen.io/aleksey_000/pen/RwaojXQ?editors=1010

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2020-08-21
@alekseyy__9090

Because it keymust be a unique value, and you use the same value for each element of the list. The easiest and most primitive way to shut up React so that it does not swear at the absence of a key is to do something like this:

taskList.map(function(item, idx) {
  return (
    <p className="task" key={idx} >{item}</p>
  )
})

But a better way is to organize the state structure in such a way that a unique key is stored in each element of the list. Something like that:
taskList = [
  {id: 1, objective: 'Buy milk'},
  {id: 2, objective: 'Learn React'},
]

taskList.map(task => (<div key={task.id}>{task.objective}</div>))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question