Reactjs 如何使用条件更改数组中特定值的状态
我想在某个条件下更改数组中的值,我尝试了几种方法,但都失败了,最后一种方法是:Reactjs 如何使用条件更改数组中特定值的状态,reactjs,Reactjs,我想在某个条件下更改数组中的值,我尝试了几种方法,但都失败了,最后一种方法是: addResponse (e) { const { current_component_id, responses, current_question_id } = this.state; this.setState(prevState => { const responses = prevState.responses.map((it
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,
}>,
};
类型状态={
当前问题:数量,
当前\u组件\u id:编号,
当前问题id:编号,
答复:阵列,
};
我想找到答案。问题id等于当前问题id并更改答案。答案组件=当前组件id这应该可以:
prevState.responses.map((item, j) => {
if (item.question_id === current_question_id) {
return {...item, answer_component: current_component_id };
}
return item;
}
我使用的是==
运算符而不是=
,第一个是比较运算符,另一个是赋值运算符
为了正确返回对象,我使用的是扩展对象表示法,它输入“if”,但返回不起作用