smallnew / react-native-multibundler

react native可视化bundle拆包,支持远程加载和debug,支持官方的0.57~0.63.2版本,使用官方的metro拆包,适用于Android、iOS
MIT License
861 stars 186 forks source link

没有执行预加载的代码会报错 #86

Open moujunqiang opened 4 years ago

moujunqiang commented 4 years ago

ReactInstanceManager reactInstanceManager = ((ReactApplication)getApplication()).getReactNativeHost().getReactInstanceManager(); if (!reactInstanceManager.hasStartedCreatingInitialContext()) { reactInstanceManager.createReactContextInBackground();//这里会先加载基础包platform.android.bundle,也可以不加载 } 如果注释掉MainActivity这段代码会报错

hexiangyuan commented 4 years ago

如果注释掉MainActivity中的这几行

ReactInstanceManager reactInstanceManager = ((ReactApplication)getApplication()).getReactNativeHost().getReactInstanceManager();
        if (!reactInstanceManager.hasStartedCreatingInitialContext()) {
            reactInstanceManager.createReactContextInBackground();
        }

会导致崩溃

修复方法是: 修改AsyncReactActivity中

//默认給null的ComponentName
  protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, null);
    }

//runApp中加载完成了Bundle再调用mDelegate.loadApp(getMainComponentName());
protected void runApp(String scriptPath){
        if(scriptPath!=null){
            scriptPath = "file://"+scriptPath.substring(0,scriptPath.lastIndexOf(File.separator)+1);
        }
        final String path = scriptPath;
        final RnBundle bundle = getBundle();
        final ReactInstanceManager reactInstanceManager = ((ReactApplication)getApplication()).getReactNativeHost().getReactInstanceManager();
        if(bundle.scriptType == ScriptType.NETWORK){//如果是网络加载的话,此时正在子线程
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ScriptLoadUtil.setJsBundleAssetPath(
                            reactInstanceManager.getCurrentReactContext(),
                            path);
                    mDelegate.loadApp(getMainComponentNameInner());
                }
            });
        } else {//主线程运行
            ScriptLoadUtil.setJsBundleAssetPath(
                    reactInstanceManager.getCurrentReactContext(),
                    path);
            mDelegate.loadApp(getMainComponentName());
        }
    }
hexiangyuan commented 4 years ago

可以参考 https://github.com/smallnew/react-native-multibundler/pull/88