以下代码用于在添加新用户后立即打印反向用户列表,但不起作用。自动运行正在侦听延迟计算的var(_userArrayRev),但是如何启用该var的重新计算?自动运行只执行一次,而我希望它运行三次
而且,为什么当enforceactions(useStrict)设置为true时,MobX允许我修改AddUser()中的observable userArray var?
import { useStrict, configure, autorun } from 'mobx';
import { observable, action, computed } from 'mobx';
configure({ enforceActions: true });
class Test {
@observable _userArray = [];
@observable _userArrayRev = undefined;
userCount = 0;
addUser() {
console.log("Adduser");
this._userArray.push('user' + this.userCount);
this.invalidateCache();
}
// returns reversed array
getUsersArrayRev() {
if (this._userArrayRev == undefined) {
// console.log("recalculating userArray");
// TODO: should be reversed
this._userArrayRev = this._userArray;
}
return this._userArrayRev;
}
invalidateCache() {
this._usersArrayRev = undefined;
}
}
var t = new Test();
autorun(function test () {
console.log("users: ", t.getUsersArrayRev());
});
t.addUser();
t.addUser();
答案 0 :(得分:1)
我建议您使用computed
代替autorun
。如果要基于computed
对象创建只读惰性变量,observable
更适合。
注意:我使用slice()
返回普通数组。可观察数组是一个对象而不是数组,请注意这一点。
import React from 'react';
import { render } from 'react-dom';
import { observer } from 'mobx-react';
import { observable, action, computed } from 'mobx';
class Test {
@observable _userArray = [];
@computed get userCount() {
return this._userArray.length;
}
@computed get usersArrayRev() {
return this._userArray.slice().reverse();
}
@action
addUser() {
console.log("Adduser");
const id = this.userCount + 1;
this._userArray.push(`user${id}`);
console.log("Reversed users: ", this.usersArrayRev);
}
}
@observer
class App extends React.Component {
t = new Test();
render() {
return (
<div>
{this.t.usersArrayRev.map(user => <div key={user}>{user}</div>)}
<button onClick={() => { this.t.addUser(); }}>Add user</button>
</div>
);
}
}
此处的代码演示: