如何使某些页面仅在首次下载应用程序时出现 - React Native

问题描述 投票:0回答:2

我正在使用 React Native 创建一个应用程序,其中有几个页面仅在首次打开应用程序时显示,这些页面包括选择语言以及允许访问位置和通知页面。

如何让这些页面在首次下载应用程序时仅出现一次。

目前,我将所有页面存储在主“App.js”文件中的堆栈中。

<NavigationContainer>
  <Stack.Navigator screenOptions={{headerShown:false}}>
    <Stack.Screen name='selectLanguage' component={selectLanguage} />
    <Stack.Screen name='setLocation' component={setLocation} />
    <Stack.Screen name='enableNotifications' component={enableNotifications} />
    <Stack.Screen name='HomePage' component={HomePage} />
  </Stack.Navigator>
</NavigationContainer>
javascript reactjs react-native stack
2个回答
0
投票

首次导航到主屏幕后,将我的案例 IntroShown 中的标志设置为 1

useEffect(()=>{AsyncStorage.setItem("IntoShown", "1")},[])

然后你的 app.js 看起来会像这样

function App() {
const Stack = createNativeStackNavigator();
const [isShown, setIsShown] = useState("0")
useEffect(() => {
    checkIntro()
}, [])

const checkIntro = async () => {
    let temp = await AsyncStorage.getItem("IntoShown")
    setIsShown(temp)
}

return (
        <Stack.Navigator screenOptions={{ headerShown: false, gestureEnabled: false }}>
            {isShown == "0" && <>
                    <Stack.Screen name='selectLanguage' component={selectLanguage} />
<Stack.Screen name='setLocation' component={setLocation} />
<Stack.Screen name='enableNotifications' component={enableNotifications} />
            </>}
<Stack.Screen name='HomePage' component={HomePage} />

) }


0
投票

你也许可以做这样的事情

  const App = () => {
  const [firstLaunch, setFirstLaunch] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    checkFirstLaunch();
  }, []);

  const checkFirstLaunch = async () => {
    const hasLaunched = await AsyncStorage.getItem('hasLaunched');
    if (hasLaunched === null) {
      await AsyncStorage.setItem('hasLaunched', 'true');
      setFirstLaunch(true);
    } else {
      setFirstLaunch(false);
    }
    setIsLoading(false);
  };

  if (isLoading) {
    return (
       <ActivityIndicator />
    );
  }

  return (
    <NavigationContainer>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        {firstLaunch ? (
          <>
            <Stack.Screen name='selectLanguage' component={selectLanguage}/>
            <Stack.Screen name='setLocation' component={setLocation} />
            <Stack.Screen name='enableNotifications' component={enableNotifications} />
              </>
          ) : (
            <Stack.Screen name='HomePage' component={HomePage} />
          )}
          </Stack.Navigator>
        </NavigationContainer>
      );
    };
© www.soinside.com 2019 - 2024. All rights reserved.