[英]MobX - Replacing item in observable array?
Please correct me if I am wrong, but currently this is not possible using replace, as replace would replace the entire observable array and map should be used instead? 如果我错了请纠正我,但目前使用replace是不可能的,因为替换会替换整个可观察数组,而应该使用map?
I have an observable array like this: 我有一个这样的可观察数组:
@observable questionsList = [];
On server call it gets populated with 2 objects, each with a distinct id
field, so it'll look like this: 在服务器调用上,它将填充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..."}
];
So the question with id of 1
has a typo which needs fixing, should be Is the earth flat?
所以id为1
的问题有一个需要修复的拼写错误,应该Is the earth flat?
Given the following: 鉴于以下内容:
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
Now I have the correct oldQuestion
but how can I replace it in the questionList
array with the new question? 现在我有正确的oldQuestion
但是如何在questionList
数组中用新问题替换它? I tried replace, but it didn't work. 我试过替换,但它没有用。 Is map the only way? 地图是唯一的方式吗? If so I am not sure how to get map to work as I've only worked with observable arrays. 如果是这样,我不知道如何使地图工作,因为我只使用可观察数组。
How can I accomplish this using MobX? 如何使用MobX完成此操作?
Each property of the observable object will in turn be observable, so you could just overwrite the string: 可观察对象的每个属性都将是可观察的,因此您可以只覆盖该字符串:
const newQuestionId = 1;
const newQuestion = "Is the earth flat?"
const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
oldQuestion.question = newQuestion;
If you have additional fields in the new question object that you would like to use instead, and make these new fields observable as well, you could use extendObservable : 如果您想在新问题对象中使用其他字段,并且也可以使这些新字段可观察,则可以使用extendObservable :
const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
extendObservable(oldQuestion, newQuestionObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.