我正在使用上下文 API 进行状态管理 我为学生设置了初始状态:null 和标签:[] student 是一个包含如下数据的对象数组:
[
{
"id": 1,
"city": "some city",
"name" : "some name",
"colors" : [
"1": "blue",
"2" : "red"
],
"age": "some age"
},
{
"id": 2,
"city": "some city",
"name" : "some name",
"colors" : [
"1": "green",
"2" : "yellow"
],
"age": "some age"
}
]
标签数组是这样的
{
"studentId": 1,
"tag": "some tag",
},
{
"studentId": 2,
"tag": "some tag",
},
{
"studentId": 2,
"tag": "some tag",
},
]
现在我想将标签数组中的对象添加到学生数组中的匹配对象中。 例如,id 为 2 的学生,他有两个带有他 id 的标签。我希望将带有 studentId 2 的标签数组作为数组添加到该特定 id 的学生对象中..不知道我是否有意义。
我的状态文件
const addTag = async tag => {
try {
dispatch({
type: ADD_TAG,
payload: tag
})
} catch (error) {
dispatch({
type: STUDENT_ERROR ,
payload: error
})
}
}
我的减速机
case ADD_TAG:
return {
...state,
tags: [...state.tags, action.payload],
}
我只是填充标签状态..但我也想为学生状态这样做。 谢谢
答案 0 :(得分:-1)
你可以简单地复制学生数组(这样你就不会直接改变它),找到有问题的学生对象的索引,然后给它添加标签。
case ADD_TAG:
let studentCopies = JSON.parse(JSON.stringify(state.students));
let index = studentCopies.findIndex(s => s.id === action.payload.studentId);
if (index > -1) {
// if student object is in array, then add tag to student's tag array
if (studentCopies[index].tags) {
studentCopies[index].tags = [...studentCopies[index].tags, action.payload];
} else {
studentCopies[index].tags = [action.payload]
}
}
return {
...state,
students: studentCopies,
tags: [...state.tags, action.payload]
}