React native architecture

From findscripter/everything-skills · View interactive version

React native architecture is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 Expo / React Native 起新项目或落地导航、状态管理、原生模块、离线优先架构与移动端性能/发布时使用;做项目结构、Expo Router、AuthProvider、React Query 离线缓存、原生能力封装、FlashList 优化与 EAS 构建发布的工程化方案产出;不适用于纯 Web 前端、Flutter/原生 iOS/Android 单端开发或与移动架构无关任务;触发词:React Native、Expo、Expo Router、EAS、离线优先、FlashList

How to use this skill

Skill file

何时使用

不该用的边界:

步骤

0. 选型:Expo 还是 Bare RN

优先 Expo(开发更快、内置 OTA、托管原生代码、EAS 构建)。仅当需大量自定义原生代码且 config plugin 无法覆盖时,才考虑 Bare RN。

| 维度 | Expo | Bare RN |

|---|---|---|

| 上手 | 低 | 高 |

| 原生模块 | EAS Build | 手动 linking |

| OTA 更新 | 内置 | 手动搭建 |

| 自定义原生代码 | Config plugins | 直接访问 |

1. 初始化与目录结构

npx create-expo-app@latest my-app -t expo-template-blank-typescript
npx expo install expo-router expo-status-bar react-native-safe-area-context
npx expo install @react-native-async-storage/async-storage
npx expo install expo-secure-store expo-haptics

推荐结构(app/ 为 Expo Router 文件路由):

src/
├── app/            # Expo Router 屏幕((auth)/ (tabs)/ _layout.tsx)
├── components/     # ui/ 通用组件 · features/ 业务组件
├── hooks/          # 自定义 hook
├── services/       # API 与原生服务封装
├── stores/         # 状态管理
├── utils/  └── types/

2. 根布局:注入全局 Provider

在 app/_layout.tsx 用 Stack 定义路由栈,并自外向内包裹 QueryProvider / ThemeProvider:

export default function RootLayout() {
  return (
    <QueryProvider>
      <ThemeProvider>
        <Stack screenOptions={{ headerShown: false }}>
          <Stack.Screen name="(tabs)" />
          <Stack.Screen name="(auth)" />
          <Stack.Screen name="modal" options={{ presentation: 'modal' }} />
        </Stack>
      </ThemeProvider>
    </QueryProvider>
  )
}

3. 导航:Expo Router

4. 鉴权流:AuthProvider 守卫路由

用 Context 暴露 user/signIn/signOut,token 存 expo-secure-store,在 useSegments() 变化时重定向(见示例 1)。

5. 离线优先:React Query + 持久化

用 PersistQueryClientProvider 把缓存写进 AsyncStorage,并用 NetInfo 同步在线状态(见示例 2)。

6. 性能与发布

指令

示例

示例 1:AuthProvider 守卫路由

export function AuthProvider({ children }) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const segments = useSegments()
  const router = useRouter()

  useEffect(() => { checkAuth() }, [])

  useEffect(() => {
    if (isLoading) return
    const inAuthGroup = segments[0] === '(auth)'
    if (!user && !inAuthGroup) router.replace('/login')
    else if (user && inAuthGroup) router.replace('/(tabs)')
  }, [user, segments, isLoading])

  async function signIn(c: Credentials) {
    const { token, user } = await api.login(c)
    await SecureStore.setItemAsync('authToken', token)
    setUser(user)
  }
  // signOut: deleteItemAsync('authToken') + setUser(null)
  if (isLoading) return <SplashScreen />
  // ...AuthContext.Provider
}

示例 2:离线优先 React Query + 乐观更新

// 同步在线状态
onlineManager.setEventListener((setOnline) =>
  NetInfo.addEventListener((s) => setOnline(!!s.isConnected))
)

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      gcTime: 1000 * 60 * 60 * 24,   // 缓存保留 24h
      staleTime: 1000 * 60 * 5,      // 5min 内视为新鲜
      retry: 2,
      networkMode: 'offlineFirst',
    },
    mutations: { networkMode: 'offlineFirst' },
  },
})
// <PersistQueryClientProvider client={queryClient}
//   persistOptions={{ persister: createAsyncStoragePersister({ storage: AsyncStorage }) }}>

// 乐观更新:onMutate 先改本地缓存并备份,onError 回滚,onSettled 重新校验
export function useCreateProduct() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: api.createProduct,
    onMutate: async (newProduct) => {
      await qc.cancelQueries({ queryKey: ['products'] })
      const previous = qc.getQueryData(['products'])
      qc.setQueryData(['products'], (old: Product[]) => [...old, { ...newProduct, id: 'temp-' + Date.now() }])
      return { previous }
    },
    onError: (_e, _v, ctx) => qc.setQueryData(['products'], ctx?.previous),
    onSettled: () => qc.invalidateQueries({ queryKey: ['products'] }),
  })
}

示例 3:原生能力封装与 EAS

// 生物识别:先探测硬件与录入,再认证
export async function authWithBiometrics() {
  if (!(await LocalAuthentication.hasHardwareAsync())) return false
  if (!(await LocalAuthentication.isEnrolledAsync())) return false
  const r = await LocalAuthentication.authenticateAsync({
    promptMessage: 'Authenticate to continue', fallbackLabel: 'Use passcode',
  })
  return r.success
}
# 构建 / 提交 / OTA
eas build --platform all --profile production
eas submit --platform ios
eas update --branch production --message "Bug fixes"

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.