Skip to content

混编下的RCTRootView加载方式 #2

Description

@ljunb

算下来转正也接近一个月了,在这里参与了两个混编项目,遇到一些坑,说实在的,自己差点就忘了做纯RN开发是什么感觉了。Σ( ° △ °|||)︴


目前正开发中的项目,是一个面向销售人员的汽车营销APP,基于公司原生技术的积累,该项目也是在原生的骨架上来开发。按目前项目分工来看,原生与RN的业务比例呈1:1分布,仍然没达到团队老大的理想效果,他期望的是2:3。RN表示我也很绝望啊,但是有些东西给原生这大佬去做,肯定是要好的嘛~

在目前的APP架构中,底部分4个Tab,其中有两个界面是由原生ViewController加载的RN界面。在实践过程中可以发现,如果在点击切换界面时才加载RNrootView,那么在第一次切换到RN界面时,就会出现短暂的白屏,非第一次则没有该问题。在与小伙伴的一番讨论之后,决定是在APP启动之后,采用预加载的形式提前渲染这两个RN界面。

其实需求比较简单,就是提前把rootView给加载出来,然后在相应ViewControllerviewDidLoad中去把保存好的rootView取出来,赋值给self.view就可以了。这里用单例形式来管理:

#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>

@interface PCReactRootViewManager : NSObject
/*
 * 获取单例
 */
+ (instancetype)manager;

/*
 * 根据viewName预加载bundle文件
 * param: 
 *     viewName RN界面名称
 *     initialProperty: 初始化参数
 */
- (void)preLoadRootViewWithName:(NSString *)viewName;
- (void)preLoadRootViewWithName:(NSString *)viewName initialProperty:(NSDictionary *)initialProperty;

/*
 * 根据viewName获取rootView
 * param:
 *     viewName RN界面名称
 *
 * return: 返回匹配的rootView
 */
- (RCTRootView *)rootViewWithName:(NSString *)viewName;

@end

在混编模式中,渲染不同的RN界面有两种方式:

  • 统一由一个ViewController加载rootView,在initialProperties中添加区分不同界面的标识位,然后在JS中根据该标识位,渲染不同的Component
  • AppRegistryregisterComponent方法中,第一个参数需要跟加载的moduleName一一对应。通过加载对应的moduleName,然后在JS中注册对应组件,也可以达到渲染不同界面的目的

我司在实践中,采用的是第二种方式。在实践中,第二种方式依然可以统一由一个ViewController来作为加载rootView的入口,也可以根据业务情况,来新建一些独立的ViewController,方便业务逻辑分离。

抛开两种方式的不同点,我们会发现,不管用哪种方式,都需要有一个新建RCTRootView实例的过程,而查看源码可知,在这之前是需要新建一个RCTBridge实例的:

// RCTRootView.m
- (instancetype)initWithBundleURL:(NSURL *)bundleURL
                       moduleName:(NSString *)moduleName
                initialProperties:(NSDictionary *)initialProperties
                    launchOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL
                                            moduleProvider:nil
                                             launchOptions:launchOptions];

  return [self initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties];
}

关于原生与RN的通信原理,网上已经有不少资料,有兴趣的伙伴戳:

所以,除了可做预加载之外,我们还可以在RCTBridge实例这里做下处理。首先让该类实现RCTBridgeDelegate协议,再添加一个bridge属性,以便不同的ViewController都可以访问到这个属性:

#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTBridge.h>

@interface PCReactRootViewManager : NSObject<RCTBridgeDelegate>

// 全局唯一的bridge
@property (nonatomic, strong, readonly) RCTBridge * bridge;

/*
 * 获取单例
 */
+ (instancetype)manager;

/*
 * 根据viewName预加载bundle文件
 * param: 
 *     viewName RN界面名称
 *     initialProperty: 初始化参数
 */
- (void)preLoadRootViewWithName:(NSString *)viewName;
- (void)preLoadRootViewWithName:(NSString *)viewName initialProperty:(NSDictionary *)initialProperty;

/*
 * 根据viewName获取rootView
 * param:
 *     viewName RN界面名称
 *
 * return: 返回匹配的rootView
 */
- (RCTRootView *)rootViewWithName:(NSString *)viewName;

@end

具体的.m文件实现:

#import "PCReactRootViewManager.h"

@interface PCReactRootViewManager ()
// 以 viewName-rootView 的形式保存需预加载的RN界面
@property (nonatomic, strong) NSMutableDictionary<NSString *, RCTRootView*> * rootViewMap;
@end

@implementation PCReactRootViewManager

- (void)dealloc {
    _rootViewMap = nil;
    [_bridge invalidate];
    _bridge = nil;
}

+ (instancetype)manager {
    static PCReactRootViewManager * _rootViewManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _rootViewManager = [[PCReactRootViewManager alloc] init];
    });
    return _rootViewManager;
}

- (instancetype)init {
    if (self = [super init]) {
        _rootViewMap = [NSMutableDictionary dictionaryWithCapacity:0];
        _bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:nil];
    }
    return self;
}

- (void)preLoadRootViewWithName:(NSString *)viewName {
    [self preLoadRootViewWithName:viewName initialProperty:nil];
}

- (void)preLoadRootViewWithName:(NSString *)viewName initialProperty:(NSDictionary *)initialProperty {
    if (!viewName && [_rootViewMap objectForKey:viewName]) {
        return;
    }
    NSMutableDictionary *tmpInitialProperty = [NSMutableDictionary dictionaryWithDictionary:initialProperty];
    [tmpInitialProperty setObject:viewName forKey:@"viewName"];
    // 由bridge创建rootView
    RCTRootView * rnView = [[RCTRootView alloc] initWithBridge:self.bridge 
                                                    moduleName:@"YourAppName" 
                                             initialProperties:initialProperty];
    [_rootViewMap setObject:rnView forKey:viewName];
}

- (RCTRootView *)rootViewWithName:(NSString *)viewName {
    if (!viewName) {
        return nil;
    }
    return [self.rootViewMap objectForKey:viewName];
}

#pragma mark - RCTBridgeDelegate
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
    return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
}

以下是预加载与读取rootView的简易方式:

// APP启动后,在合适时机加载
[[PCReactRootViewManager manager] preLoadRootViewWithName:@"discovery"];
[[PCReactRootViewManager manager] preLoadRootViewWithName:@"mine"];

// 渲染界面时,获取rootView
self.view = [[PCReactRootViewManager manager] rootViewWithName:@"discovery"];

普通的RN界面渲染方式:

- (void)setupRootView {
    NSString * moduleName = [self.initialProperty objectForKey:@"viewName"];
    if (!moduleName || ![moduleName isKindOfClass:[NSString class]]) {
        NSLog(@"viewName为空,无法加载rootView");
        return;
    }
    // 设置初始属性
    [self configInitialProperties];

    // 根据唯一的bridge来创建rootView,减少新建bridge的时间和资源开销
    RCTRootView * rnView = [[RCTRootView alloc] initWithBridge:[PCReactRootViewManager manager].bridge
                                                    moduleName:@"YourAppName"
                                             initialProperties:self.initialProperty];
    self.view = rnView;
}

在 JavaScript 端:

// index.js
...
AppRegistry.registerComponent('YourAppName', () => Root);


// Root.js
class Root extends React.Component {
  render() {
    const { viewName } = this.props;
    if (viewName === 'Page1') {
      return <Page1 />;
    } else if (viewName === 'Page2') {
      return <Page2 />;
    }
  }
}

如果项目中还集成了 react-navigation 的话,入口文件需要修改为:

import { createStackNavigator } from 'react-navigation';
const createNavigatorWithInitialRouteName = (initialRouteName = 'Splash') => createStackNavigator(
{
  PageA: {},
  ...
}, {
  initialRouteName,
  ...
});

export default class NavigatorContainer extends React.Component {
  constructor(props) {
    super(props);
    this.Navigator = createNavigatorWithInitialRouteName(props.viewName);
  }
  
  render() {
    const { Navigator } = this;
    return <Navigator />;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions