【问题标题】:React native variable state is being preserved only on some screensReact 本机变量状态仅在某些屏幕上保留
【发布时间】: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


    【解决方案1】:

    react 中的导航作为堆栈工作后进先出。

    组件中的状态会一直存在,直到它被 react 卸载

    在您的第一个示例中,Recipe 是堆栈的根,然后您将收藏夹添加到堆栈中并将其删除。在此操作期间,配方仍安装在您的导航中,因此状态被保留

    在第二个示例中,收藏夹是导航中的最后一个组件。 当您返回食谱时,组件收藏夹将被卸载并且状态丢失。当您再次返回收藏夹时,组件会以默认状态值挂载。

    您可以在此document 中搜索更多信息。

    【讨论】:

    • 哦,好的,我了解@docmurloc,谢谢。那么这个导航是我想做的错误方法吗?我应该怎么做才能随意在屏幕之间导航而不让它们重置变量状态?
    • 如果你想保留你的状态,你必须用contextreact redux将它保存在你的组件之外
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多