使用AsyncStorage/Jotai修改存储时,能否在Stack导航器头部显示ActivityIndicator?
问题解答
1. AsyncStorage存储时在页面头部显示ActivityIndicator
完全可以实现,核心是通过状态变量控制加载状态,再将状态传递给Stack导航器的头部组件。
实现思路:
- 用
useState声明isLoading状态变量,初始值为false - 执行AsyncStorage操作前将
isLoading设为true,操作完成(成功/失败)后重置为false - 自定义Stack导航器的头部元素,根据
isLoading状态决定是否渲染ActivityIndicator
代码示例:
import { useState, useEffect } from 'react'; import { AsyncStorage, ActivityIndicator, Button } from 'react-native'; import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); function StorageScreen({ navigation }) { const [isLoading, setIsLoading] = useState(false); const saveData = async () => { setIsLoading(true); try { await AsyncStorage.setItem('user_info', JSON.stringify({ name: 'test' })); } catch (err) { // 处理存储错误 } finally { setIsLoading(false); } }; // 动态设置头部右侧元素 useEffect(() => { navigation.setOptions({ headerRight: () => ( isLoading ? <ActivityIndicator style={{ marginRight: 12 }} /> : null ), }); }, [navigation, isLoading]); return ( <Button title="保存数据" onPress={saveData} /> ); } function AppNavigator() { return ( <Stack.Navigator> <Stack.Screen name="Storage" component={StorageScreen} /> </Stack.Navigator> ); }
2. Jotai修改存储时在Stack头部展示ActivityIndicator
可以实现,利用Jotai的全局原子跟踪加载状态,在修改存储的逻辑中更新原子状态,再在页面组件中订阅状态并传递给头部。
实现思路:
- 创建全局的
isSavingAtom原子,用于管理加载状态 - 在修改存储的异步函数中,先将
isSavingAtom设为true,操作完成后重置为false - 在目标页面用
useAtom获取状态,动态配置Stack导航器的头部
代码示例:
import { atom, useAtom } from 'jotai'; import { AsyncStorage, ActivityIndicator, Button, Text } from 'react-native'; import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); // 全局加载状态原子 const isSavingAtom = atom(false); // 带加载状态的存储修改函数 const updateStorageWithJotai = async (set) => { set(isSavingAtom, true); try { await AsyncStorage.setItem('settings', JSON.stringify({ theme: 'dark' })); // 同步更新其他Jotai原子(如果需要) } catch (err) { // 处理错误 } finally { set(isSavingAtom, false); } }; function JotaiScreen({ navigation }) { const [isSaving] = useAtom(isSavingAtom); const [, setAtom] = useAtom(isSavingAtom); useEffect(() => { navigation.setOptions({ headerTitle: () => ( isSaving ? ( <ActivityIndicator color="#ffffff" /> ) : ( <Text>设置页面</Text> ) ), }); }, [navigation, isSaving]); return ( <Button title="更新设置" onPress={() => updateStorageWithJotai(setAtom)} /> ); } function AppNavigator() { return ( <Stack.Navigator> <Stack.Screen name="JotaiSettings" component={JotaiScreen} /> </Stack.Navigator> ); }
内容的提问来源于stack exchange,提问作者BenoHiT
相关产品推荐
相关产品推荐

