我在点击Reactjs按钮的同时推动对象。最初我有三种类型的对象,如“LOCAL”,“GLOBAL”和“MAIN”。我在onclock回调中将这些名称作为参数传递。如何避免使用reactJs插入重复项?
我的渲染代码,
<div>
<input type="checkbox" onClick={this.checkedIn.bind(this, "LOCAL", "12")} />
<button type="checkbox" onClick={this.checkedIn.bind(this, "GLOBAL", "15")} />
<button type="checkbox" onClick={this.checkedIn.bind(this, "MAIN", "11")} />
<button type="checkbox" onClick={this.checkedIn.bind(this, "MAIN", "13")} />
</div>
onclick事件
var objectVale = [];
checkedIn(type, value) {
objectVale.push({
type:type,
value:[value]
})
}
期待输出,
[
{
"type":"LOCAL",
"value":[12]
},
{
"type":"GLOBAL",
"value":[15]
},
{
"type":"MAIN",
"value":[11, 13]
}
]
答案 0 :(得分:1)
问题是你正在推动每个点击事件的价值。相反,首先使用type
查找数组并找到必要的对象,然后将值推送到此对象的值数组。
var o = objectVale.find(function(x) {
return x.type === type;
})
if (o) {
o.value = o.value || [];
o.value.push(value);
} else {
objectVale.push({
type: type,
value: [value]
})
}
答案 1 :(得分:1)
您可以尝试这样的事情:
var objectVale = [];
checkedIn(type, value) {
var index = objectValue.findIndex(function(obj){ return obj.type === type; });
if(index === -1){ // Object with the specific type not found.
objectValue.push({
type:type,
value:[value]
})
} else { // Object with the specific type found. So push only the value.
objectValue[index].value.push(value)
}
}