数组中不可变更新助手的动态键 [英] Dynamic key in immutability update helper for array
问题描述
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计算的属性名称,这将与您的索引
变量相似:
updateValue(index,e){
pre>
var items = React.addons.update(this.state.items,{
[index]:{
amount:{ $ set:e.target.value}
}
})
this.setState({items})
}
根据此 ES6兼容性表,Reac当它的Harmony变换启用时,t的JSX transpiler支持它们,或者您可以使用 Babel (自对于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,{
金额:{$ set:e.target.value}
}
))
this.setState({items:items})
}
https://facebook.github.io/react/docs/update.html
I have an update function that receives an index along with the event so as to alter the value for that specific item in the array.
How do I get
index
to be evaluated instead of treated as a set key in this scenario? Is it even possible?updateValue: function(index, e) { var items = React.addons.update(this.state.items, { index: { amount: {$set: e.target.value} } }); this.setState({ items: items }) }
Right now this obviously doesn't work because it's attempting to update
this.state.items['index']['amount']
which is not set, when I want to modifythis.state.items[1]['amount']
for an index of 1.解决方案You could use ES6 computed property names, which would look like this with your
index
variable:updateValue(index, e) { var items = React.addons.update(this.state.items, { [index]: { amount: {$set: e.target.value} } }) this.setState({items}) }
According to this ES6 compatability table, React's JSX transpiler supports them when its Harmony transforms are enabled, or you could use Babel instead (since react-tools is being deprecated in favour of Babel anyway).
Failing that, you could use a helper function to create an object with a given named property:
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}) }
这篇关于数组中不可变更新助手的动态键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!