admin 管理员组文章数量: 1086019
I have this class:
class Board {
this.state = {
lists : [{
id: 0,
title: 'To Do',
cards : [{id : 0}]
}]
}
And want to use setState on the 'cards' array inside of the 'lists' state array. Previously, I had the cards array in a child ponent but I have now moved it up to the Board class. This is the function that I had before.
deleteCards(id){
this.setState({
cards: this.state.cards.filter(card => card.id !== id)
});
}
How can I change it so that it works now that cards is inside another array?
I was unable to solve it looking at these posts:
ReactJS - setState of Object key in Array
How to edit an item in a state array?
I have this class:
class Board {
this.state = {
lists : [{
id: 0,
title: 'To Do',
cards : [{id : 0}]
}]
}
And want to use setState on the 'cards' array inside of the 'lists' state array. Previously, I had the cards array in a child ponent but I have now moved it up to the Board class. This is the function that I had before.
deleteCards(id){
this.setState({
cards: this.state.cards.filter(card => card.id !== id)
});
}
How can I change it so that it works now that cards is inside another array?
I was unable to solve it looking at these posts:
ReactJS - setState of Object key in Array
How to edit an item in a state array?
Share Improve this question edited Jul 20, 2018 at 0:57 D. Seah 4,5921 gold badge13 silver badges25 bronze badges asked Jul 19, 2018 at 23:44 Chick EvansChick Evans 471 silver badge8 bronze badges2 Answers
Reset to default 5To do it all within setState
(note that the first argument to setState
is an updater function where its first argument is a reference to the previous state):
If you can provide the listId
from the caller:
deleteCards(listId, cardId) {
this.setState(prevState => ({
lists: prevState.lists.map((list) => {
if (list.id !== listId) {
return list
}
return {
...list,
cards: list.cards.filter(card => card.id !== cardId)
}
})
}))
}
If you can not provide the listId
from the caller:
deleteCards(id) {
this.setState(prevState => ({
lists: prevState.lists.map((list) => {
if (list.cards.some(card => card.id === id)) {
return {
...list,
cards: list.cards.filter(card => card.id !== id)
}
}
return list
})
}))
}
You should attempt to use the new rest and spread syntax...
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const newListItem = {this.state.lists[0].cards.filter....}
this.setState({lists: [...this.state.lists.cards, newListItem]})
I would have made this a ment but it would be pretty hard to read. This is just an example you need to actually write a filter.
本文标签: javascriptSet state of nested arrayStack Overflow
版权声明:本文标题:javascript - Set state of nested array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744026059a2520651.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论