我是本地反应的新手。我面临着将数据推送到数组中的问题。我有一个数组位置,在这个数组中我有一个名为记分表的子数组。在记分表数组中,我有一些数据。当我尝试在特定索引上的记分表数组中推送数据时,它总是将数据推送到每个位置的记分表中。
我试图将数据推送到数组中:
this.state.locations[1].scoreSheets[0].categories.push({
subscore:0
});
locations: Array(34)
0: {location_id: "23", name: "Salad bar", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
1: {location_id: "24", name: "Grill Station ", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
2: {location_id: "25", name: "Entrée station", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
3: {location_id: "26", name: "Action station", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
4: {location_id: "27", name: "Sushi Station", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
5: {location_id: "28", name: "Soup station ", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
6: {location_id: "29", name: "Specialty station ", scoreSheets: Array(2), foodInspections: Array(0), refrigerations: Array(0)}
每当尝试推送预期结果时,都会将数据推送到位置数组的第一个索引,然后推送到记分表数组的第 0 个索引,但它将数据推送到每个位置。
您的 scoreSheets 对象可能引用到相同的类别对象。每个 scoreSheets 对象都需要是一个不同的对象。为每个记分表对象分配一个新的类别数组。例:
var newScoreSheets = [...categories]
分配新的类别数组,而不是引用同一对象