如果我错了,请纠正我,但目前使用 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
数组中的它?我试过更换,但没有用。 map 是唯一的方法吗?如果是这样,我不确定如何让 map 工作,因为我只使用过可观察数组。
我如何使用 MobX 完成此操作?
最佳答案
observable 对象的每个属性都将依次是 observable,因此您可以只覆盖字符串:
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);
关于javascript - MobX - 替换可观察数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543194/