【发布时间】:2021-04-02 21:01:02
【问题描述】:
我刚刚开始使用 React Native。我有 2 个屏幕(收藏夹和食谱),只有一个 const valor 和基本上完全相同的代码,除了用于在屏幕之间导航的第二个按钮。
问题:
如果我使用第一个按钮在“食谱”屏幕中增加 valor 的值,导航到收藏夹并返回到食谱一切正常,该值仍然是我设置的最后一个值。但是,如果我导航到收藏夹,更改那里的值,转到食谱并返回收藏夹,则收藏夹屏幕上的值将重置回 1。这是为什么呢?
const RecipesScreen = ({navigation}) => {
const [ valor, setValor ] = useState(1);
return (
<View style={{flex: 1}}>
<Text style={{top: 100}}>variable is recipes is now { valor }</Text>
<View style={{marginTop: 140}} >
<Button onPress={ () => { setValor(valor+1); }} title="INCREMENT"></Button>
<Button onPress={ () => { navigation.navigate("Favorites"); }} title="Go to favorites"></Button>
</View>
</View>
);
}
const FavoritesScreen = ({navigation}) => {
const [ valor, setValor ] = useState(1);
return (
<View style={{flex: 1}}>
<Text style={{top: 100}}>variable is favorites is now { valor }</Text>
<View style={{marginTop: 140}} >
<Button onPress={ () => { setValor(valor+1); }} title="INCREMENT"></Button>
<Button onPress={ () => { navigation.navigate("Recipes"); }} title="Go to recipes"></Button>
</View>
</View>
);
}
import RecipesScreen from './RecipesScreen.js';
import FavoritesScreen from './FavoritesScreen.js';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator screenOptions={{animationEnabled: false, headerShown: false }} >
<Stack.Screen name="Recipes" component={RecipesScreen} />
<Stack.Screen name="Favorites" component={FavoritesScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
【问题讨论】:
标签: react-native navigation screen reset