【问题标题】:Two RCTRootView instances in one app一个应用中的两个 RCTRootView 实例
【发布时间】:2016-01-01 00:39:36
【问题描述】:

我正在编写一个有两个视图的 iOS 应用程序。每个视图都是一个 RCTRootView,由不同的 React Native 组件创建。

我调查了这个问题 (Multiple RCTRootView in a single App),所以现在我知道这是可能的。

但是有一个问题。让第一个 RCTRootView 实例是 B,让第二个是 B。A 首先显示在屏幕上,它的 react-native 对应物使用 NativeAppEventEmitter 从我的原生应用程序接收事件。在这一点上,一切正常。 A还有一个按钮可以在屏幕上显示B。

按下按钮时,会创建并显示 B。当再次按下按钮时,B 从其父视图中移除并销毁。

但在此之后,NativeAppEventEmitter 什么也不做。

欢迎任何形式的提示或 cmets。

【问题讨论】:

    标签: ios react-native


    【解决方案1】:

    此问题与 self.bridge 为 nil 的症状有关。虽然我做了@synthesize bridge = _bridge,但在从javascript端处理事件时,bridge属性为nil,这是出乎意料的。

    通过检查和上网,我找到了原因:对于RCTBridgeModule,objective-c代码很难控制对象的生命周期。关于桥接模块的最佳实践是忘记有关其生命周期的所有细节,并且不要对其生命周期做出任何假设。

    所以,如果您自己创建了桥接模块(可能使用[MyBridge new]),您的应用程序中可能有两个不同的桥接对象。您无法确定哪个对象会从 javascript 端接收事件。

    因此,我现在正在使用以下解决方案。

    @implementation EventBridge
    
    @synthesize bridge = _bridge;
    
    RCT_EXPORT_MODULE();
    
    - (instancetype) init {
      self = [super init];
      if ( self ) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(cartUpdateNotification:)
                                                     name:kCartUpdateNotification
                                                   object:nil];
      }
      return self;
    }
    
    + (void) addObserver:(id)observer selector:(SEL)selector {
      [[NSNotificationCenter defaultCenter] addObserver:observer
                                               selector:selector
                                                   name:kMenuClickNotification
                                                 object:nil];
    }
    
    /*
     * objc -> js call 
     */
    + (void) postEventWithName:(NSString *)name object:(id)object {
      [[NSNotificationCenter defaultCenter]
          postNotification:[NSNotification notificationWithName:name
                                                         object:object]];
    }
    
    /*
     * js -> objc call when the hamburger is clicked
     */
    RCT_EXPORT_METHOD(menuClicked)
    {
      // This method might be called on the different TopNavViewController object.
      [[NSNotificationCenter defaultCenter] postNotificationName:kMenuClickNotification
                                                          object:nil];
    }
    
    - (void) cartUpdateNotification:(NSNotification*)notification {
      [self.bridge.eventDispatcher sendAppEventWithName:@"CartUpdated" body:@{@"item":notification.object}];
    }
    
    @end
    

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多