问题描述
https://codesandbox.io/s/polished-bird-662mh
我有一个对象数组和一个具有以下结构的对象
I am having this an array of objects and an object with the following structure
this.state = {
arr : [ {
id: "val1",
initialVal: "test1",
finalVal: "final1"
},
{
id: "val2",
initialVal: "test2",
finalVal: "final2"
},
{
id: "val3",
initialVal: "test3",
finalVal: "final3"
},
{
id: "val4",
initialVal: "test3",
finalVal: "final3"
}
],
values: [ "test1","test3"]
}
this.obj = { field: "test1" , val:6}
我正在编写一个函数,将该obj作为其参数,并根据"field"值,应通过以下计算将obj的"val"属性设置为"finalVal"状态(如果val大于5在该字段中添加"ok",否则添加"cancel"),其属性在"values"状态数组中不匹配的对象的"finalVal"应设置为空白
I am writing a function that takes this obj as its parameter and based on the "field" value it should set the state of "finalVal" with the "val" property of obj with the following computation(if val is greater than 5 add "ok" to the field else add "cancel") and the objects whose property don't match in the "values" array of the state its "finalVal" should be set to just blank
因此输出应注意设置状态:
So the output should look after setting state :
[
{
id: "val1",
initialVal: "test1",
finalVal: "ok"
},
{
id: "val2",
initialVal: "test2"
finalVal: "final2"
},
{
id: "val3",
initialVal: "test3"
finalVal: ""
},
{
id: "val4",
initialVal: "test4"
finalVal: "final4"
}
]
//What I have tried so far
setObjState = obj => {
console.log(obj);
let arr = [...this.state.arr];
let finalArr = arr.map(function(item) {
if (item.initialVal === obj.field) {
return { ...item, finalVal: obj.val > 5 ? "Cancel" : "Ok" };
} else {
if(this.state.values.includes(item.id){
return { ...item, finalVal: "" };
}
}
});
console.log(finalArr);
this.setState({ arr: finalArr });
}
推荐答案
首先,您需要使用map函数来更新新状态.
First thing you need map function to update new state.
您只需要解决此问题:
setObjState = obj => {
console.log(obj);
let arr = [...this.state.arr];
let finalArr = arr.map(function(item) {
if (item.initialVal === obj.field) {
return { ...item, finalVal: obj.val > 5 ? "Cancel" : "Ok" };
} else {
return { ...item, finalVal: "" };
}
});
console.log(finalArr);
this.setState({ arr: finalArr });
}
这里是完整的代码和演示: https://codesandbox.io/s/nervous- hodgkin-uxhoi
Here is full code and demo : https://codesandbox.io/s/nervous-hodgkin-uxhoi
这篇关于根据匹配在对象数组内设置对象的属性:React JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!