我想在一定条件下更改数组中的值,我尝试了几种方法,但我不能,最后尝试的方法是这样:
addResponse (e) {
const { current_component_id, responses, current_question_id
} = this.state;
this.setState(prevState => {
const responses = prevState.responses.map((item, j) => {
if (item.question_id === current_question_id) {
return item.answer_component = current_component_id
}
})
})
};
这是我的状态:
type State = {
current_question: number,
current_component_id: number,
current_question_id: number,
responses: Array<{
enrollment_id: number,
evaluation_id: number,
question_id: number,
answer_component: number,
user_id: number,
}>,
};
我想找到与current_question_id相等的response.question_id并更改响应。answer_component= current_component_id
答案 0 :(得分:1)
这应该有效:
prevState.responses.map((item, j) => {
if (item.question_id === current_question_id) {
return {...item, answer_component: current_component_id };
}
return item;
}
我使用===
运算符而不是=
,第一个是比较运算符,另一个是赋值。
为了正确返回对象,我使用了传播对象符号