【发布时间】:2020-06-06 07:23:12
【问题描述】:
我正在尝试更新我的状态以包含新的信息对象如果该新信息对象的名称与状态中的一个名称相同。比如……
当有新信息时:
{
serviceName:
name: A
properties:{
cost: 300
service:"Good"
}
}
匹配现有状态的名称:
{
serviceName:
name: A
properties:{
cost: 600
service:"Bad"
}
}
目标是我可以合并 just 属性,结果是:
{
serviceName:
name: A
properties:{
cost: [300,600]
service:["Good", "Bad"]
}
}
我在第一场比赛中得到的最接近的作品,但随后的比赛会产生一个数组数组,就像这样(三个项目匹配,所以应该有一个包含 3 项成本和服务的数组):
{
"name": "State",
"value": [
{
"serviceName": {
"name": "Informational Website - subscription",
"properties": {
"service": [
[
"Mobile-ready, Responsive Design",
"Blog Articles"
],
"Collect visitor information (email / phone)"
],
"cost": [
[
"300",
"500"
],
"500"
]
}
}
}
],
"subHooks": []
},
我通过以下代码实现了上述目标:
const [informationalService, setInformationalService] = useState([]);
const handleChecking = (e, item) => {
const { name } = e.target;
if (informationalService.length > 0) {
const selectedName = informationalService.filter(
selection => selection.serviceName.name === name
);
const selectedNamePropertiesCost = selectedName.map(
prop => prop.serviceName.properties.cost
);
const selectedNamePropertiesService = selectedName.map(
prop => prop.serviceName.properties.service
);
const notSelectedName = informationalService.filter(
selection => selection.serviceName.name !== name
);
const serviceChecked = selectedName.filter(
selected => selected.serviceName.properties.service !== item.service
);
setInformationalService([
...notSelectedName,
{
serviceName: {
name,
properties: {
service: [...selectedNamePropertiesService, item.service],
cost: [...selectedNamePropertiesCost, item.cost]
}
}
}
]);
} else {
setInformationalService([
{
serviceName: {
name,
properties: {
service: item.service,
cost: item.cost
}
}
}
]);
}
};
【问题讨论】:
-
我建议
service和cost的值使用一致的数据类型。在您的情况下,初始值应该是一个包含一项的数组。当您需要更改它时,您可以将新项目推送到数组中。 -
@Hoyen,谢谢。您能否详细说明一下使用一致数据类型的值是什么意思?你的意思是在我的示例成本:[300],服务:[“好”]?
标签: javascript reactjs react-hooks react-state-management use-state