RN - mobx的集成

作者: iOS_杨平 | 来源:发表于2018-10-05 16:31 被阅读10次

    mobx和redux同为状态管理工具。

    redux写法复杂,状态越多,需要写的Type、Action、reducer就越多,大大增加了代码的复杂度。

    mobx使用简单,代码精简,个人强烈推荐!!!

    下面说一下mobx的集成:

    1.在工程目录下安装需要的依赖:mobxmobx-react

    npm i mobx mobx-react --save

    2.安装 babel 插件,以支持 ES7 的 decorator 特性:

    npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save -dev

    3.需要安装下面的4个babel库,因为从0.56版本开始,react-native默认支持bable7,之前的写法都不对了。

     npm i @babel/core @babel/plugin-proposal-decorators @babel/plugin-transform-runtime @babel/runtime --save

    4.修改.babelrc文件,完成下面这步就可以正常的使用装饰器啦!

    {

      "presets": ["module:metro-react-native-babel-preset"],

      "plugins": [

        ["@babel/plugin-proposal-decorators", { "legacy": true }],

        ["@babel/transform-runtime", {

          "helpers": true,

          "regenerator": false

        }]

      ]

    }

    5.修复App入口文件,默认是index.js。这也是个bug,如果不添加如下代码,会导致release包无法正常运行。

    import applyDecoratedDescriptor from '@babel/runtime/helpers/esm/applyDecoratedDescriptor';

    import initializerDefineProperty from '@babel/runtime/helpers/esm/initializerDefineProperty';

    Object.assign(babelHelpers, { applyDecoratedDescriptor, initializerDefineProperty });

    import {AppRegistry} from 'react-native';

    import Root from './src/Root';

    import {name as appName} from './app.json';

    AppRegistry.registerComponent(appName, () => Root);

    集成过程中参考了这篇文章

    tip: ES7装饰器语法在编译器可能会报错, 解决办法:

    首选项-->设置-->工作区设置,加入以下代码:

    "javascript.implicitProjectConfig.experimentalDecorators": true

    vscode截图

    相关文章

      网友评论

        本文标题:RN - mobx的集成

        本文链接:https://www.haomeiwen.com/subject/epyqaftx.html