mobx:更改数据时的类方法调用

问题描述

Сan我使用Mobx库在数据更改时调用方法吗?

例如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

您还可以使用其他方法来实现所需的目标: