你提到的 React Native 网络、存储与原生能力,属于 React Native 开发中的三个核心模块。我给你整理一份系统知识框架:

一、React Native 网络能力

React Native 本身提供基于 JavaScript 的网络访问能力,主要使用:

1. Fetch API(官方推荐)

类似浏览器 Fetch:

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

POST 请求:

fetch('https://api.example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'admin',
    password: '123456'
  })
})
.then(res => res.json())
.then(data => console.log(data));

2. Axios

实际项目更常用:

安装:

npm install axios

使用:

import axios from 'axios';

axios.get('/api/user')
  .then(res => {
    console.log(res.data);
  });

封装实例:

const request = axios.create({
  baseURL: 'https://api.xxx.com',
  timeout: 10000
});

request.interceptors.request.use(config => {
  config.headers.Authorization = token;
  return config;
});

export default request;

常用于:

  • Token 自动添加

  • 请求重试

  • 错误统一处理

  • Loading 管理


3. 网络状态检测

使用:

npm install @react-native-community/netinfo

示例:

import NetInfo from '@react-native-community/netinfo';

NetInfo.addEventListener(state => {
  console.log(state.isConnected);
});

应用场景:

  • 无网络提示

  • 离线缓存

  • 网络切换处理


二、React Native 数据存储

React Native 没有浏览器的 localStorage,需要使用原生存储方案。

1. AsyncStorage(最常用)

安装:

npm install @react-native-async-storage/async-storage

保存:

import AsyncStorage from '@react-native-async-storage/async-storage';

await AsyncStorage.setItem(
  'username',
  'zhangsan'
);

读取:

const name = await AsyncStorage.getItem('username');

console.log(name);

删除:

await AsyncStorage.removeItem('username');

适合:

✅ 用户配置
✅ Token
✅ 简单缓存

不适合:

❌ 大量数据
❌ 高性能查询


2. Secure Storage(安全存储)

用于:

  • Access Token

  • Refresh Token

  • 密钥

常见库:

  • Keychain(iOS)

  • Keystore(Android)

例如:

npm install react-native-keychain

保存:

Keychain.setGenericPassword(
  'user',
  'token123'
);

底层:

React Native
      |
      |
Native Module
      |
 ----------------
 |              |
iOS Keychain Android Keystore

3. SQLite 数据库

适合:

  • 聊天记录

  • 商品列表

  • 离线数据

常用:

npm install react-native-sqlite-storage

示例:

db.transaction(tx=>{
  tx.executeSql(
    'CREATE TABLE User(id INTEGER,name TEXT)'
  );
});

结构:

SQLite

User
--------------
id | name
1  | Tom
2  | Jack

4. MMKV 高性能存储

目前 React Native 项目常用:

MMKV

特点:

  • C++实现

  • 内存映射

  • 比 AsyncStorage 快很多

示例:

storage.set(
  'token',
  'abc123'
);

storage.getString('token');

适合:

  • 大量 Key-Value

  • 高频读写


三、React Native 原生能力

React Native 最大特点:

JavaScript 写业务,Native 提供系统能力。

架构:

          JavaScript

              |
              |
        React Native Bridge

              |
    ---------------------
    |                   |
 Android Native      iOS Native

 Java/Kotlin         Swift/Obj-C

1. 调用系统能力

例如:

相机

库:

npm install react-native-camera

使用:

<Camera
  captureAudio={false}
/>

能力:

  • 拍照

  • 扫码

  • 视频


定位

常用:

npm install react-native-geolocation-service

代码:

Geolocation.getCurrentPosition(
 position=>{
   console.log(
    position.coords.latitude
   );
 }
);

文件系统

库:

npm install react-native-fs

读取:

RNFS.readFile(path)
.then(content=>{
 console.log(content);
});

应用:

  • 下载文件

  • 图片缓存

  • 上传


2. Native Module 原生模块

当 RN 没有能力时,需要自己写 Native Module。

例如:

JS:

NativeModules.DeviceInfo.getBattery()

Android:

@ReactMethod
public void getBattery(
 Promise promise
){
 promise.resolve(80);
}

JS 调用:

JavaScript
    |
    |
NativeModules
    |
    |
Android/iOS代码

3. Native UI Component

如果需要原生控件:

例如:

  • 高性能地图

  • 视频播放器

  • AR

  • 图表

流程:

React Component

      ↓

View Manager

      ↓

Native View

      ↓

Android/iOS UI

四、常见项目技术组合

实际 App 常见组合:

需求 方案
HTTP请求 Axios
接口缓存 React Query
Token保存 Keychain/MMKV
普通缓存 AsyncStorage
数据库 SQLite
图片缓存 FastImage
网络状态 NetInfo
定位 Geolocation
扫码 Camera
推送 Firebase/APNs
原生功能 Native Module

五、React Native 面试重点

常问:

1. RN如何和Native通信?

答案:

通过 Bridge:

JS Thread
   |
Bridge
   |
Native Module

新版架构:

  • JSI

  • TurboModules

  • Fabric


2. AsyncStorage安全吗?

不是。

原因:

  • 明文存储

  • 可被读取

敏感信息应该:

Token
 ↓
Keychain / Keystore

3. RN如何实现离线?

方案:

网络请求
    |
    |
缓存层
    |
 ----------------
 |              |
MMKV          SQLite

流程:

  1. 先读缓存

  2. 请求服务器

  3. 更新缓存

  4. 无网使用缓存


4. Bridge为什么慢?

传统:

JS
 ↓
JSON序列化
 ↓
Bridge
 ↓
Native

存在:

  • 数据转换

  • 异步通信

  • 线程切换

新版:

JSI
 ↓
C++ Runtime
 ↓
Native

减少通信成本。


总结

React Native 的核心能力可以记成:

网络
 |
 |-- Fetch
 |-- Axios
 |-- NetInfo


存储
 |
 |-- AsyncStorage
 |-- MMKV
 |-- SQLite
 |-- Keychain


原生能力
 |
 |-- Camera
 |-- GPS
 |-- File
 |-- Push
 |-- Native Module
 |-- Native UI

掌握这三部分,基本覆盖 React Native 真实项目开发的 70% 常用能力。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐