F
F
Faraday_222018-04-16 20:14:04
JavaScript
Faraday_22, 2018-04-16 20:14:04

What is the correct way to remove an object in an array when updating the state of a component?

for example, we have an array of objects of the form

let users= [
    {
        "id": 0,
        "user": "qwe",
    },
    {
        "id": 1,
        "user": "qwe1",
    },
    {
        "id": 2,
        "user": "qwe2",
    }
 ]

display elements in the component
let user = this.props.users.map(function(user){
      return <li key={user.id}><User number={user.id} text={user.id}/></li>
 })

We have a list of user components and each has a delete button. How to correctly implement the removal of one element?
For example, how to remove an element
{
    "id": 0,
    "user": "qwe",
}

so that when the state is updated, the remaining 2 are displayed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-04-16
@Faraday_22

The array is stored in state.
When clicking on the button "cross" - call the handler, for example onDeleteClick(which is a method of your class)

state = {
  users: [/*.. массив с юзерами*/]
}
...
onDeleteClick = (e) => {
  const id = e.currentTarget.dataset.myId
  const новый_массив =  массив_без_удаленного_элемента (подсказка, удалять можно через фильтрацию по айди)
  this.setState({ users: новый_массив })
}
...
let user = this.props.users.map(function(user){
      return <li key={user.id}><User number={user.id} id={user.id} text={user.id} onDeleteClick={this.onDeleteClick}/></li>
 })
...
// где-то там в компоненте User (что там внутри не знаю, но предположим есть кнопка удаления как вы пишите)
...
render() {
 <div>
 // что-то по верстке про юзера
   <button onClick={this.props.onDeleteClick} data-my-index={this.props.user.id}> Удалить</button>
 </div>
}

The main idea: the state (the list of users) is stored in the parent in the state. To delete, you must send a function from the parent, as one of the props, in order to change the state inside this function (in the parent). In order to understand which user to delete, pass some sign, for example, id from the native data-* attribute, which you yourself set by passing id as props from the parent when drawing User

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question