2023年6月27日发(作者:)
ReactNativeAndroid⽩屏优化终极⽅案本⽅案适⽤于Android原⽣项⽬集成React Native框架。问题描述我们公司的APP部分模块使⽤了react native进⾏开发,使⽤react native开发确实很爽,⼀次编写到处运⾏,前端的开发体验,⾼效的开发效率,但是我们进⼊react native模块的时候,会有明显的⽩屏,时间⼤概是1-2s,这是很差的⽤户体验,我们今天的这篇⽂章就是为了解决这个痛点。已有⽅案我相信很多同学可能都看过react native中⽂⽹推荐的这篇⽂章,这篇⽂章⽅案很给⼒!作者采⽤了内存换时间的⽅案,缓存了ReactInstanceManager和ReactRootView对象,我们只需要在应⽤启动的时候初始化,之后进⼊react native模块都是调⽤缓存⾥的数据,所以速度⾮常快。此⽅案存在的⼩问题但是试过的同学可能知道这个⽅案有个⼩问题:第⼀次进⼊react native模块之后,再次进⼊react native模块,react native 页⾯的⽣命周期都不会执⾏(render, componentDidMount等),因为我们拿的都是已经缓存好的数据,假如我们在react native页⾯请求数据更新页⾯,只有第⼀次进⼊的时候是有效的。改进⽅案因为发现了这个问题,所以在github上⾯向作者提了issue,作者给了耐⼼解答,所以把改进⽅案分享给⼤家,省的⼤家⾛弯路。这篇⽂章还是原作者cnsnake11的智⼒成果,我只是做个分享以及简化了⼀点点代码。我们这篇⽂章的重点是Android⽩屏优化,关于Android原⽣项⽬集成react native,请看我另⼀篇⽂章。我们现在的⽅案就是只缓存ReactInstanceManager,每次进⼊ReactActivity的时候新建⼀个ReactRootView对象。具体代码如下:public class RNCacheViewManager { private static ReactInstanceManager mManager = null; //init public static void init(Context context) { mManager = createReactInstanceManager(); ReactRootView mRootView = new ReactRootView(context); eactApplication(mManager, "test", null); } public static ReactInstanceManager getReactInstanceManager() { return mManager; } private static ReactInstanceManager createReactInstanceManager() { return r() .setApplication(tance()) .setBundleAssetName("") .setJSMainModuleName("d") .addPackage(new MainReactPackage()) .setUseDeveloperSupport(true) //开发者⽀持,开发的时候要设置为true,不然⽆法使⽤开发者菜单 .setInitialLifecycleState(D) .build(); }}我们这个类主要负责初始化ReactInstanceManager对象,我们可以在APP启动的时候进⾏初始化(调⽤init函数),然后我们在⾃⼰的ReactActivity中进⾏调⽤。public class ReactRootActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler { private ReactRootView mReactRootView; private ReactInstanceManager mReactInstanceManager; @Override protected void onCreate(Bundle savedInstanceState) { te(savedInstanceState); mReactRootView = new ReactRootView(this); mReactInstanceManager = ctInstanceManager(); Bundle bundle = getIntent().getExtras(); eactApplication(mReactInstanceManager, "test", bundle); setContentView(mReactRootView); } @Override public void invokeDefaultOnBackPressed() { Pressed(); } @Override protected void onPause() { e(); if (mReactInstanceManager != null) { Pause(this); } } @Override protected void onResume() { me(); if (mReactInstanceManager != null) { Resume(this, this); } } @Override protected void onDestroy() { roy(); if (mReactInstanceManager != null) { Destroy(this); } } @Override public void onBackPressed() { if (mReactInstanceManager != null) { Pressed(); } else { Pressed(); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == E_MENU && mReactInstanceManager != null) { vOptionsDialog(); return true; } return p(keyCode, event); }}总结这个问题耽误了我很长的时间,所以我想把我的⼼路历程分享给⼤家,这样⼤家遇到这个问题的时候就可以分分钟搞定,如果我有说的什么不清楚的地⽅,尽管提问。
发布者:admin,转转请注明出处:http://www.yc00.com/news/1687842544a50033.html
评论列表(0条)