MobX - 替换可观察数组中的项目?

MobX - Replacing item in observable array?

如果我错了请纠正我,但目前使用 replace 是不可能的,因为 replace 会替换整个 observable 数组,应该使用 map 代替?

我有一个这样的可观察数组:

@observable questionsList = [];

在服务器调用时,它填充了 2 个对象,每个对象都有一个不同的 id 字段,因此它看起来像这样:

@observable questionsList = [
                             {id: 1,
                              question: "Is the earth flats?",
                              answer: "Some long answer here..."
                             {id: 2,
                              question: "Does the moon have life?"}
                              answer: "Some long answer here..."}
                            ];

所以id为1的问题有错别字需要修改,应该是Is the earth flat?

鉴于以下情况:

const newQuestionId = 1;
const newQuestion = "Is the earth flat?"
const oldQuestion = this.questionsList.find(question => question.id === newQuestionId);
oldQuestion.replace(newQuestion) // Would be nice if this syntax worked

现在我有了正确的 oldQuestion,但如何用新问题替换 questionList 数组中的它?我试过更换,但没有用。地图是唯一的方法吗?如果是这样,我不确定如何让地图工作,因为我只使用过可观察数组。

我如何使用 MobX 完成此操作?

可观察对象的每个 属性 反过来也是可观察的,因此您可以只覆盖字符串:

const newQuestionId = 1;
const newQuestion = "Is the earth flat?"
const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
oldQuestion.question = newQuestion;

如果您希望使用新问题对象中的其他字段,并使这些新字段也可观察,您可以使用 extendObservable:

const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
extendObservable(oldQuestion, newQuestionObject);