gpt4 book ai didi

javascript - 数组的不变性更新助手中的动态键

转载 作者:IT王子 更新时间:2023-10-29 03:19:10 25 4
gpt4 key购买 nike

https://facebook.github.io/react/docs/update.html

我有一个更新函数,它接收一个索引和事件,以便更改数组中该特定项目的值。

我如何获得 index在这种情况下被评估而不是被视为设置键?有可能吗?

updateValue: function(index, e) {
var items = React.addons.update(this.state.items, {
index: {
amount: {$set: e.target.value}
}
});
this.setState({
items: items
})
}

现在这显然不起作用,因为它正在尝试更新 this.state.items['index']['amount']未设置,当我想修改this.state.items[1]['amount']索引为 1。

最佳答案

你可以使用 ES6 computed property names ,它看起来像你的 index 变量:

updateValue(index, e) {
var items = React.addons.update(this.state.items, {
[index]: {
amount: {$set: e.target.value}
}
})
this.setState({items})
}

根据这个ES6 compatability table , React 的 JSX 转换器在启用 Harmony 转换时支持它们,或者你可以使用 Babel相反(自 react-tools is being deprecated in favour of Babel 起)。

否则,您可以使用辅助函数来创建具有给定命名属性的对象:

function makeProp(prop, value) {
var obj = {}
obj[prop] = value
return obj
}

// ...

updateValue: function(index, e) {
var items = React.addons.update(this.state.items, makeProp(
index, {
amount: {$set: e.target.value}
}
))
this.setState({items: items})
}

关于javascript - 数组的不变性更新助手中的动态键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899454/

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