【发布时间】:2021-03-14 19:40:53
【问题描述】:
Codesandbox 的问题: https://codesandbox.io/s/serverless-thunder-6gj04?file=/src/store.js
我有以下商店:
class PersonStore {
persons = [];
constructor() {
makeAutoObservable(this, {}, { autoBind: true });
}
*fetchPersons() {
const response = yield fetch(
"https://random-data-api.com/api/users/random_user?size=5"
);
this.persons = yield response.json();
}
}
export default new PersonStore();
现在,我想更新人员列表中的人员。
当我像这样在数组内的项目上更新单个字段时,它会按预期工作并且 UI 会更新:
update(id) {
let updated = this.persons.find((p) => p.id === id);
// This works...
updated.first_name = "FOO";
}
但是,将来我想将更复杂的更新数据传递给这个函数。所以我的想法是基本上用列表中的更新值分配一个全新的对象。
不幸的是,这并没有像我预期的那样工作:
update(id) {
let updated = this.persons.find((p) => p.id === id);
// This does not work...
const dummy_person = { first_name: 'foo', last_name: 'bar', id: 99 }
updated = dummy_person
}
我的第一个猜测是这不起作用,因为数组中的对象不是“普通对象”而是可观察的。所以我为这些人创建了一个模型:
class Person {
id = null;
first_name = "";
last_name = "";
constructor() {
makeAutoObservable(this);
this.first_name = "FOO";
this.last_name = "BAR";
}
}
...但这仍然不起作用...
update(id) {
let updated = this.persons.find((p) => p.id === id);
// This does not work...
const dummy_person = new Person()
updated = person
}
如何将此处的数组中的对象“替换”为包含更新数据的对象?
【问题讨论】:
-
当您编写
updated = dummy_person时,您只是用新值更新updated引用。 MobX 在那个阶段没有参与。你可以尝试这样的事情:let updatedIndex = this.persons.findIndex((p) => p.id === id); this.persons.splice(updatedIndex, 1, dummy_person);
标签: javascript reactjs mobx mobx-react