gpt4 book ai didi

javascript - 如何从setState中的数组中选择特定对象?

转载 作者:行者123 更新时间:2023-12-01 01:58:07 26 4
gpt4 key购买 nike

class Example extends React.Component{
constructor(props){
super(props);
this.state = {
array: [{n: 0}, {n: 1}, {n: 2}]
}
}

selectObjectFromArray = index => {
this.setState({
array: //???
})
}

我们只知道索引,我们要在数组中编辑对象。我们不能像 this.state.array[1] = ... 那样做,也不能做 setState({array[1]:... .我考虑过像这样的传播:array: [...this.state.array,,但是在这种情况下,我们无法设置我们要编辑的位置。那么我们该怎么办在这种情况下?

最佳答案

We only know the index, where we want to edit the object in the array

给定一个knownIndex

this.setState({
array:
[ ...this.state.array.slice (0, knownIndex) // <-- items up to the index
, someUpdate(this.state.array[knownIndex])) // <-- updated object
, ...this.state.array.slice (knownIndex + 1) // <-- items after the index
]
})

另一种方法是使用数组 .map 函数。我们也将其设为通用函数

const updateAtIndex = (xs, i, f) =>
xs .map ((x, j) => i === j ? f (x) : x)

在你的组件中,你可以像这样使用它

this.setState ({
array: updateAtIndex (this.state.array, knownIndex, f)
})

其中f是一些更新对象的函数,例如

// returns a new object with the n property doubled
const f = obj =>
({ n: obj.n * 2 })
<小时/>

在编写泛型函数时,我喜欢让它们变得更加健壮。如果您在程序中使用此技术,我建议对上述函数进行一些更改。这些更改更有效地传达参数类型,并允许读者更好地推断函数返回类型。

const identity = x =>
x

const updateAtIndex = (xs = [], i = 0, f = identity) =>
xs .map ((x, j) => i === j ? f (x) : x)

const f = ({ n = 0 }) =>
({ n: n * 2 })

关于javascript - 如何从setState中的数组中选择特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840674/

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