-
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
class TestData {
list: any[] = [];
listIndex = -1;
constructor() {
makeAutoObservable(this);
}
get activeItem() {
return this.list.reduce((result, item, index, arr) => {
if (index === this.listIndex) {
result = item;
// End the loop early
arr.splice(1);
}
return result;
});
}
changeIndex() {
this.listIndex += 1;
}
changeListData() {
this.list[0].list[0] = { a: 1, b: 2 };
}
changeList() {
this.list.push({
id: Math.floor(Math.random() * 100000),
data: {},
list: [{ a: 1 }],
});
}
}
const testData = new TestData();
const TestComponent = observer(() => {
const item = testData.activeItem;
if (!item) {
return null;
}
return (
<div>
{item.id} {item.list}
</div>
);
}); The computed activeItem will not respond correctly, what do I need to do to achieve this function? |
Beta Was this translation helpful? Give feedback.
Answered by
urugator
Oct 19, 2021
Replies: 1 comment 8 replies
-
Dunno what the intention is, but get activeItem() {
return this.list[this.listIndex];
} |
Beta Was this translation helpful? Give feedback.
8 replies
Answer selected by
StringKe
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dunno what the intention is, but
computed
shouldn't mutate observables (arr.splice(1)
). Maybe you just wanna do the following?