mobx: class 更改数据时调用方法
mobx: class method call when changing data
当数据发生变化时,我可以使用 Mobx 库调用 class 方法吗?
例如 MyObject
写入 container['item'] = 10
结果调用了 myaction
方法。
class MyElement extends Component<any> {
// modifiable data
container: any = [];
// method called when data (container) is modified
myaction() {
console.log('container was modified');
console.log(this.container);
}
render() {
<MyObject container = {this.container} />
}
}
decorate(MyElement, {
container: observable
} as any)
您可以使用 reaction
例如:
container = [];
componentDidMount() {
// save disposer function to use later inside componentWillUnmount
this.reactionDisposer = reaction(
() => this.container.length,
() => {
console.log('container was modified')
}
);
}
// Don't forget to dispose it when unmount
componentWillUnmount() {
this.reactionDisposer();
}
Codesandbox link: https://codesandbox.io/s/httpsWhosebugcomquestions63864175-kjorh?file=/src/App.js
此外,从技术上讲,您可以使用数组 container['item'] = 10
来做到这一点,但我建议您不要将字符串键与数组一起使用。如果要使用字符串键,则需要使用对象或 Map
.
您还可以使用其他方法来实现您想要的效果:
-
当(基本是单次使用反应)- https://mobx.js.org/refguide/when.html
或较低级别的内容,例如 observe
和 intercept
- https://mobx.js.org/refguide/observe.html
当数据发生变化时,我可以使用 Mobx 库调用 class 方法吗?
例如 MyObject
写入 container['item'] = 10
结果调用了 myaction
方法。
class MyElement extends Component<any> {
// modifiable data
container: any = [];
// method called when data (container) is modified
myaction() {
console.log('container was modified');
console.log(this.container);
}
render() {
<MyObject container = {this.container} />
}
}
decorate(MyElement, {
container: observable
} as any)
您可以使用 reaction
例如:
container = [];
componentDidMount() {
// save disposer function to use later inside componentWillUnmount
this.reactionDisposer = reaction(
() => this.container.length,
() => {
console.log('container was modified')
}
);
}
// Don't forget to dispose it when unmount
componentWillUnmount() {
this.reactionDisposer();
}
Codesandbox link: https://codesandbox.io/s/httpsWhosebugcomquestions63864175-kjorh?file=/src/App.js
此外,从技术上讲,您可以使用数组 container['item'] = 10
来做到这一点,但我建议您不要将字符串键与数组一起使用。如果要使用字符串键,则需要使用对象或 Map
.
您还可以使用其他方法来实现您想要的效果:
当(基本是单次使用反应)- https://mobx.js.org/refguide/when.html
或较低级别的内容,例如
observe
和intercept
- https://mobx.js.org/refguide/observe.html