微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何解决反应本机EventEmitterListener警告

我正在使用事件发射器在地图组件和工具栏之间进行通信.注意*我在我的应用程序的其他部分使用相同的代码,没有问题.我得到的错误是:

Warning: setState(…): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

我已经尝试通过类似的帖子解决这个问题,但它不工作.我以为这跟安装&&&在两个组件中卸载方法

工具栏组件

componentDidMount() {
    this.showLocateIconListener = AppEventEmitter.addListener('isTrip',this.isTrip.bind(this));
    this.endTripListener = AppEventEmitter.addListener('showLocateIcon',this.showLocateIcon.bind(this));
    this.endSubdivisionIcon = AppEventEmitter.addListener('showSubdivisionIcon',this.showSubdivisionIcon.bind(this));
}

componentwillUnMount() {
    this.showLocateIconListener.remove();
    this.endTripListener.remove();
    this.endSubdivisionIcon.remove();
}


 //// this is where the error is happening
showSubdivisionIcon(val) {
    if (val != 0)
        this.setState({
            items: menuSubdivision,subdivisionId: val
        })
    else
        this.setState({
            items: menu
        })
}

地图组件

onMarkerPress(val) {
    AppEventEmitter.emit('showSubdivisionIcon',val.id);
}

EventEmitter.js的控制台错误详细信息导致这一点

subscription.listener.apply(
        subscription.context,Array.prototype.slice.call(arguments,1)
      );

EventEmitter.js中的完整部分

/**
   * Emits an event of the given type with the given data. All handlers of that
   * particular type will be notified.
   *
   * @param {string} eventType - Name of the event to emit
   * @param {...*} Arbitrary arguments to be passed to each registered listener
   *
   * @example
   *   emitter.addListener('someEvent',function(message) {
   *     console.log(message);
   *   });
   *
   *   emitter.emit('someEvent','abc'); // logs 'abc'
   */
  emit(eventType: String) {
    var subscriptions = this._subscriber.getSubscriptionsForType(eventType);
    if (subscriptions) {
      var keys = Object.keys(subscriptions);
      for (var ii = 0; ii < keys.length; ii++) {
        var key = keys[ii];
        var subscription = subscriptions[key];

        // The subscription may have been removed during this event loop.
        if (subscription) {
          this._currentSubscription = subscription;
          subscription.listener.apply(
            subscription.context,1)
          );
        }
      }
      this._currentSubscription = null;
    }
  }

解决方法

唯一的问题是您的事件侦听器不会被删除,因为componentwillUnmount方法名称不正确.在你的代码中,M是Mount,它应该是小写的.
componentwillUnmount() {
    this.showLocateIconListener.remove();
    this.endTripListener.remove();
    this.endSubdivisionIcon.remove();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐