Answer the question
In order to leave comments, you need to log in
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",
}
]
let user = this.props.users.map(function(user){
return <li key={user.id}><User number={user.id} text={user.id}/></li>
})
{
"id": 0,
"user": "qwe",
}
Answer the question
In order to leave comments, you need to log in
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>
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question