gpt4 book ai didi

javascript - 如何在reactjs中设置状态特定参数的特定值

转载 作者:行者123 更新时间:2023-12-01 16:09:47 27 4
gpt4 key购买 nike

this.state = {
array: [1, 2, 3],
objects: [{ id: 1 }, { id: 2 }, { id: 3 }]
}

如何在不设置整个数组/对象的情况下更改状态中对象或数组的特定值?

有点像

this.setState({ array[2]: 5 })
this.setState({ object[0].id: 0 })

最佳答案

您可以使用辅助函数在索引处设置元素并返回新更新的数组

const array = [1, 2, 3]
const object = [{id: 1}, {id: 2}, {id: 3}]

const setElementAtIndex = (index, value, array) => [
...array.slice(0, index),
value,
...array.slice(index + 1)
]

console.log(setElementAtIndex(0, 99, array))
console.log(setElementAtIndex(1, 99, array))
console.log(setElementAtIndex(2, 99, array))
console.log(setElementAtIndex(0, { ...object[0], id: 0 }, object))

this.setState({ array: setElementAtIndex(2, 5, array) })
this.setState({ object: setElementAtIndex(0, { ...object[0], id: 0 }, object) })

关于javascript - 如何在reactjs中设置状态特定参数的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63372706/

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