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

Won*_*nka 7 javascript mobx

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

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

@observable questionsList = [];
Run Code Online (Sandbox Code Playgroud)

在服务器调用上,它将填充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..."}
                            ];
Run Code Online (Sandbox Code Playgroud)

所以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
Run Code Online (Sandbox Code Playgroud)

现在我有正确的oldQuestion但我怎么能用questionList新问题在数组中替换它 ?我试过替换,但它没有用.地图是唯一的方式吗?如果是这样,我不知道如何使地图工作,因为我只使用可观察数组.

如何使用MobX完成此操作?

Tho*_*lle 8

可观察对象的每个属性都将是可观察的,因此您可以只覆盖该字符串:

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

如果您想要在新问题对象中使用其他字段,并且也可以使这些新字段可观察,则可以使用extendObservable:

const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
extendObservable(oldQuestion, newQuestionObject);
Run Code Online (Sandbox Code Playgroud)