mobx数据注入与监听

3,149 阅读1分钟

最近项目直接上手mobx,有一些困惑,做了 一些研究。下面简单介绍下inject和observer以及context的几种用法:

定义store如下:

export class UserStore implements IUserStore {

  @observable change = false;

  toggleChange = () => {
    this.change = !this.change;
  }
}

组件内使用方式分为以下几种:

1、仅使用inject

const Home1: React.SFC<IProps> = props => {
  const { toggleChange, change } = props;
  return (
    <div>
      <p>test function</p>
      <a onClick={toggleChange}>aaa</a>
      <p>{change ? "true" : "false"}</p>
    </div>
  );
};

export default inject((stores: GlobalStores) => ({
  toggleChange: stores.userstore.toggleChange,
  change: stores.userstore.change
}))(withRouter(Home1));

因为inject底层调用的是observer,因此仅使用inject也可实现。仅使用inject的情况下, inject的参数必须是所需要的属性组成的对象,否则无法observer。

2、inject和observer使用

const Home1: React.SFC<IProps> = props => {
  const { toggleChange, change } = props.userstore;
  return (
    <div>
      <p>test function</p>
      <a onClick={toggleChange}>1aaa</a>
      <p>{change ? "true" : "false"}</p>
    </div>
  );
};

export default inject((stores: GlobalStores) => ({
  userstore: stores.userstore
}))(withRouter(observer(Home1)));

inject和observer混合使用的情况下,inject的参数可以是所需要的对象组成的对象。因为observer可监控所使用的属性的变更。

3、observer和context混合使用,class定义组件

class Home1 extends React.Component<IProps> {
  static contextTypes = {
    mobxStores: PropTypes.object
  };

  render() {
    console.log(this.context, this.props, "111");
    const {
      mobxStores: {
        userstore: { toggleChange, change }
      }
    } = this.context;
    return (
      <div>
        <p>test class</p>
        <a onClick={toggleChange}>btn</a>
        <p>{change ? "true" : "false"}</p>
      </div>
    );
  }
}
export default withRouter(observer(Home1));

mobx基于context实现,因此使用observer与context可获取根节点传递下来的store

4、observer和context混合使用,function定义组件

const Home1: React.SFC<IProps> = (props, context) => {
  const {
    mobxStores: {
      userstore: { toggleChange, change }
    }
  } = context;
  return (
    <div>
      <p>test function</p>
      <a onClick={toggleChange}>aaa</a>
      <p>{change ? "true" : "false"}</p>
    </div>
  );
};

Home1.contextTypes = {
  mobxStores: PropTypes.object
};
export default withRouter(observer(Home1));