我正在使用 React Native 和 Expo 处理用户配置文件。每次我想要保存更改并查看它们的外观时,我都会被重定向到主页。然后,我必须手动导航回手机上的个人资料屏幕才能查看更改。
我已经尝试过快速刷新、热重载,并设置了到个人资料屏幕的初始路线,以便于访问。尽管做出了这些努力,但每次都这样做仍然感觉很复杂
您可以尝试状态持久化。
您可以在应用程序重新加载时保存和恢复导航状态。这可确保您在重新加载后仍保留在个人资料屏幕上。
请考虑以下示例供您参考。
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AsyncStorage from '@react-native-async-storage/async-storage';
const Stack = createStackNavigator();
const PERSISTENCE_KEY = 'NAVIGATION_STATE';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Profile"
onPress={() => navigation.navigate('Profile')}
/>
</View>
);
}
function ProfileScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Profile Screen</Text>
</View>
);
}
export default function App() {
const [isLoading, setIsLoading] = useState(true);
const [initialState, setInitialState] = useState();
useEffect(() => {
const restoreState = async () => {
try {
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString ? JSON.parse(savedStateString) : undefined;
if (state) {
setInitialState(state);
}
} finally {
setIsLoading(false);
}
};
if (isLoading) {
restoreState();
}
}, [isLoading]);
if (isLoading) {
return null; // or a loading spinner
}
return (
<NavigationContainer
initialState={initialState}
onStateChange={(state) =>
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))
}
>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
希望它能减轻您的编码体验。