乐闻世界logo
搜索文章和话题

如何在 React Native 中使用 Zustand 管理状态?

3月7日 11:44

React Native 中使用 Zustand 的方法:

  1. 安装 Zustand

    bash
    npm install zustand # 或 yarn add zustand
  2. 创建 Store

    javascript
    import { create } from 'zustand'; const useCounterStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }));
  3. 在 React Native 组件中使用

    javascript
    import React from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; import { useCounterStore } from './store'; export default function CounterScreen() { const count = useCounterStore((state) => state.count); const increment = useCounterStore((state) => state.increment); const decrement = useCounterStore((state) => state.decrement); return ( <View style={styles.container}> <Text style={styles.count}>{count}</Text> <View style={styles.buttons}> <TouchableOpacity style={styles.button} onPress={decrement}> <Text style={styles.buttonText}>-</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={increment}> <Text style={styles.buttonText}>+</Text> </TouchableOpacity> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, count: { fontSize: 48, marginBottom: 20, }, buttons: { flexDirection: 'row', gap: 20, }, button: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8, }, buttonText: { color: 'white', fontSize: 24, fontWeight: 'bold', }, });
  4. 持久化状态

    • 使用 persist 中间件保存状态到 AsyncStorage
    • 示例:
      javascript
      import { create } from 'zustand'; import { persist } from 'zustand/middleware'; import AsyncStorage from '@react-native-async-storage/async-storage'; const useUserStore = create( persist( (set) => ({ user: null, setUser: (user) => set({ user }), }), { name: 'user-storage', storage: { getItem: async (name) => { const item = await AsyncStorage.getItem(name); return item ? JSON.parse(item) : null; }, setItem: async (name, value) => { await AsyncStorage.setItem(name, JSON.stringify(value)); }, removeItem: async (name) => { await AsyncStorage.removeItem(name); }, }, } ) );
  5. React Native 特定优化

    • 避免在选择器中使用复杂计算
    • 合理使用 useCallback 缓存回调函数
    • 注意 AsyncStorage 的性能影响
  6. 常见使用场景

    • 用户认证状态管理
    • 应用设置和偏好
    • 购物车状态
    • 导航状态管理
标签:Zustand