无法获得mobx自动运行,反应,何时重新触发多次

时间:2017-07-12 15:06:47

标签: javascript reactjs react-native mobx mobx-react

我有一个呈现null的简单组件,但是当来自通知存储的shown道具更改为true时,它应该显示iOS / Android警报,它只使用一次使用autorun / reaction /来自mobx并且我可以通过spy看到hideNotification也被正确解雇以将shown设置为false,但我无法重新触发警报。

组件

import { Component } from "react";
import { observer, inject } from "mobx-react/native";
import { reaction } from "mobx";
import { Alert } from "react-native";

@inject("notification")
@observer
class Notification extends Component {
  // -- methods ------------------------------------------------------------- //
  componentDidMount() {
    reaction(
      () => this.props.notification.shown,
      () => {
        if (this.props.notification.shown)
          Alert.alert(
            this.props.notification.type,
            this.props.notification.message,
            [
              {
                text: "Close",
                onPress: this.props.notification.hideNotification
              }
            ]
          );
      }
    );
  }

  // -- render -------------------------------------------------------------- //
  render() {
    return null;
  }
}

export default Notification;

存储

import { observable, action } from "mobx";

const ERROR = "notification/ERROR";
const SUCCESS = "notification/SUCCESS";

class NotificationStore {
  // -- store --------------------------------------------------------------- //
  @observable type = ERROR;
  @observable message = "";
  @observable shown = false;

  // -- actions ------------------------------------------------------------- //
  @action
  errorNotification(message) {
    this.type = ERROR;
    this.message = message;
    this.shown = true;
  }

  @action
  successNotification(message) {
    this.type = SUCCESS;
    this.message = message;
    this.shown = true;
  }

  @action
  hideNotification() {
    this.shown = false;
  }
}

export default NotificationStore;

1 个答案:

答案 0 :(得分:0)

问题是类功能没有正确绑定,将它们改为

@action
  errorNotification = (message) => {
    this.type = ERROR;
    this.message = message;
    this.shown = true;
  }

为我解决了这个问题