问题描述
例如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链接:https://codesandbox.io/s/httpsstackoverflowcomquestions63864175-kjorh?file=/src/App.js
而且,从技术上讲,您可以使用数组container['item'] = 10
来做到这一点,但我建议您不要对数组使用字符串键。如果要使用字符串键,则需要使用object或Map
。
您还可以使用其他方法来实现所需的目标:
-
何时(基本上是一次性使用反应)-https://mobx.js.org/refguide/when.html
-
或更底层的东西,例如
observe
和intercept
-https://mobx.js.org/refguide/observe.html