react-native 开发笔记

127 阅读2分钟

RN开发脚手架相对于之前已经大开方便之门,容易了很多.... 第一步请扶稳梯子

一、基础配置

脚手架

reactnative.cn/docs/enviro… 按步骤进行配置,之所以不选择 expo 框架是因为他封装太厉害,无法打出jsbundle,灵活度欠缺,使用灵活度更高的@react-native-community/cli 来创建。

npx @react-native-community/cli init AwesomeProject

路由

路由参考 Expo 采用react-native-auto-route ,默认以 app 目录作为主路由文件夹,具体参考:howljs.github.io/react-nativ…

数据共享采用@reduxjs/toolkit

数据共享还有Recoil架构,在未来新项目中可以考虑平替 redux

数据请求

数据请求采用Axios,在实际开发当中同 swaggerAPI 下有一款开源自研组件 isoftstone-swagger-to-ts 具体参考:juejin.cn/post/731522…

二、android 和 ios 配置

启动命令配置

build 发布 jsbundle 时可以指定到native 端具体路径下:

{
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "build:android": "npx react-native bundle --platform android --dev false  --minify true --entry-file index.js --bundle-output ./android/app/src/main/assets/index.android.bundle",
    "build:ios": "npx react-native bundle --platform ios --dev false  --minify true --entry-file index.js --bundle-output ./ios/main.jsbundle",
    "commit": "git add . && czg && git push"
  },
}
  • 问题: 在配置生成 ios 包和 android 时因为 ios 一直安装失败,在清除以后重新安装 并copy 到当前项目下,因两次安装名称不同造成启动失败,在翻看源码时发现,ios->AppDelegate.mm 文件中 self.moduleName 和 react 不符。
  • 解决: 通过 node 来动态修改根目录下 app.json 重命名即可
const path = require('path');
const fs = require('fs');
const yargs = require('yargs');
let app = {
  name: 'app', // android 名称为app ios名称为 AwesomeProject
  displayName: 'app',
};

// 定义命令行参数
const argv = yargs
  .option('device', {
    alias: 'd',
    describe: '设备android或ios',
    demandOption: true,
    type: 'string', // "android" | "ios"
  })
  .help()
  .alias('help', 'h').argv;

if (argv.device == 'android') {
  console.log('android');
  app = {
    name: 'app',
    displayName: 'app',
  };
} else if (argv.device == 'ios') {
  console.log('ios');
  app = {
    name: 'AwesomeProject',
    displayName: 'AwesomeProject',
  };
} else {
  console.log('请输入正确的环境变量');
}

fs.writeFileSync(path.join(__dirname, 'app.json'), JSON.stringify(app, null), {
  encoding: 'utf-8',
});

实际开发中问题及解决

在非路由 screen 跳转解决Error: Couldn't find a navigation object

  • 问题: 实现一个 Layout 结构是 头|内容(路由)|底部导航,因rn 路由只能在 screen 中进行跳转否则会提示Error: Couldn't find a navigation object
  • 解决 使用 ref来调用navigate跳转
// refRouter.current?.navigate?.('路由');
<RouterRoot ref={refRouter} />

通过工具查看路由 name 名称也就是跳转 screen 名称:例子refRouter.current?.navigate?.('edit/index');

image.png