在MobX中,如何在不重新设置每个值的情况下为整个可观察数组设置新值?
首先想到的是:
let arr = observable([]);
autorun(() => {
console.log('my array changed!');
});
arr = ['foo', 'bar'];
但这不会触发autorun
,我只会删除observable array
并将其替换为新值/数组。
那么,这样做的正确方法是什么?
我的解决方法是使用另一个带有 setter 的变量,并在 setter函数中用更改observable array index > index ,替换,添加和删除索引。像这样:
const {observable, computed, extendObservable} = mobx;
const {observer} = mobxReact;
const {Component} = React;
const {render} = ReactDOM
const {autorun} = mobx
class Store {
@observable entries = [1,2,3,4,5];
set rows(arr) {
// add new values
for (let i = 0, l = arr.length; i < l; i++) {
this.entries[i] = arr[i];
}
// remove rest of entries
let diff = this.entries.length - arr.length;
if (diff > 0) {
while (diff > 0) {
this.entries.pop();
diff--;
}
}
}
}
const store = new Store();
@observer
class App extends Component {
updateRows(){
return this.props.entries.map(
(row, i) => <p key={i}>{row}</p>
);
}
render() {
const rows = this.updateRows();
return <div>{rows}</div>;
}
}
setTimeout(() => {
store.rows = ['foo', 'bar'];
document.body.innerHTML += 'Timeout fired...';
}, 1000);
render(
<App entries={store.entries} />,
document.getElementById('mount')
);
这是正确的方法吗?
或者有没有办法只使用相同的变量为整个数组重新赋值?
答案 0 :(得分:9)
TLDR; 使用store.entries.replace(['foo', 'bar']);
我找到了一个方法.replace()
,它将替换整个数组的内容并触发渲染。我发现它after a suggestion关于clear()
方法,并从那里仔细查看the docs
.replace(newItems);
用新的条目替换数组中的所有现有条目。
代码看起来像这样:
(jsFiddle)
const {observable, autorun} = mobx;
class Store {
@observable arr = [1,2,3,4,5];
}
const store = new Store();
autorun(() => {
console.log('my array changed!', store.arr.slice());
});
setTimeout(() => {
store.arr.replace(['foo', 'bar']);
}, 1000);
整个代码将是:
(jsFiddle)
const {observable, computed, extendObservable} = mobx;
const {observer} = mobxReact;
const {Component} = React;
const {render} = ReactDOM
const {autorun} = mobx
class Store {
@observable entries = [1,2,3,4,5];
}
const store = new Store();
@observer
class App extends Component {
updateRows(){
return this.props.entries.map(
(row, i) => <p key={i}>{row}</p>
);
}
render() {
const rows = this.updateRows();
return <div>{rows}</div>;
}
}
setTimeout(() => {
store.entries.replace(['foo', 'bar']);
}, 1000);
render(
<App entries={store.entries} />,
document.getElementById('mount')
);