React Native 导航认证屏幕

问题描述 投票:0回答:1
export default function App() {
  async function getStore(){
    try {
      const value = await AsyncStorage.getItem('my-auth');
      if (value !== null) {
        console.log('he',value)
      return true
      }
    } catch (e) {
      // error reading value
    }
  
  }
 const token=getStore();
  return (
  
<Provider store={store}>
<MenuProvider>
    <NavigationContainer>
      <Stack.Navigator initialRouteName='Screen1' screenOptions={{
    headerShown: false,
  }} >
{token ?
      <Stack.Screen name="Screen1"  options={{  animation:'slide_from_right' }} component={Screen1}  />
      <Stack.Screen name="Screen2"  options={{  animation:'slide_from_right' }} component={Screen2}  />
      <Stack.Screen name="Screen3"  options={{  animation:'slide_from_right' }} component={Screen3}  />
:
      <Stack.Screen name="Login"  options={{  animation:'slide_from_right' }} component={Screen1}  />
      <Stack.Screen name="Register"  options={{  animation:'slide_from_right' }} component={Screen2}  />
}


      </Stack.Navigator>    
    </NavigationContainer><StatusBar hidden/>
    </MenuProvider></Provider>
  );
} 

当 AsyncStorage 中存在令牌时,我需要访问经过身份验证的屏幕,否则需要访问登录和注册屏幕。当我像文档中给出的那样实现它时, getStore() 函数在从第二个堆栈成功登录后不会更新,因此不会更改堆栈。在文档中,它会自动更改屏幕,但它并没有这样做。 (https://reactnavigation.org/docs/auth-flow/)我如何在 App.js 中进行这项工作,如何确保在删除令牌后登录和注销时堆栈使用以下代码进行更改,任何洞察力会有所帮助,谢谢!

react-native react-native-navigation
1个回答
0
投票

虽然你正在阅读令牌,但 React 对此没有任何线索。 [1]

这是因为您将令牌存储在普通变量中

const token = getStore();

要让 React 意识到这一点,您要做的是将令牌存储在一个状态中,并在您的

getStore()
函数上更新此状态。

const [token, setToken] = useState('');

async function getStore() {
    try {
      const value = await AsyncStorage.getItem('my-auth');
      if (value !== null) {
        console.log('he',value);
        setToken(value); // set the token if its available
        return true
      }
    } catch (e) {
      // error reading value
    }
  
  }

然后您可以使用

useEffect
初始化挂载上的令牌。

...

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

...

通过这些更改,React 将了解

token
的值并相应地进行渲染。

P.S 使用 useCallback 包装 getStore 函数时,您可能会遇到一些 linter 错误。相应地执行所有这些操作。

参考资料:

1:https://react.dev/learn/state-a-components-memory#when-a-regular-variable-isnt-enough

© www.soinside.com 2019 - 2024. All rights reserved.