gpt4 book ai didi

javascript - 如何在循环中推送对象数组中的值?

转载 作者:行者123 更新时间:2023-12-03 00:17:35 26 4
gpt4 key购买 nike

如何在循环中将数组推送到处于 react 状态的对象列表中?

我的默认状态:

this.state = {
users: [
{
id:1,
name: 'John'
},
{
id:2,
name: 'Nick'
}
]
};

我尝试过类似的方法,但不起作用

changeHandler (currentUser, newValue) {
const users = this.state.users;
for (var i in users) {
if (users[i].id == currentUser) {
this.setState({
users: [...this.state.users[i], {newValue: newValue}]
})
}
break;
}
}

所以我希望看到:

default state - {id:1,name: 'John'},{id:2, name: 'Nick'} 
use changeHandler(2,1) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1]}
use changeHandler(2,2) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2]}
use changeHandler(2,3) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2,3]}

最佳答案

您可以使用扩展语法来映射和更新状态,例如

changeHandler (currentUser, newValue) {
const users = this.state.users;
this.setState(prevState => ({
users: prevState.users.map((user => {
if (user.id == currentUser) {
return {
...user,
newValue: [...(user.newValue || []), newValue]
}
}
return user
}))
}))
}

关于javascript - 如何在循环中推送对象数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com