首页 > 解决方案 > 我如何将令牌传递给我的子组件反应原生

问题描述

我在如何获取我的登录组件中的令牌并将其保存到现在已完成的应用程序组件时遇到问题,我无法注销,因为我不知道如何从本地存储中获取令牌并且我不知道不知道如何将它传递到另一个屏幕并在那里捕捉它。这是我的应用程序组件:

const App = () => {
  const [userToken, setUserToken] = useState(0);
  useEffect(() => {
    AsyncStorage.getItem('token').then((value) => {
      if (value) {
        setUserToken(value);
      }
    });
  }, []);
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {userToken == null ? (
          <>
            <Stack.Screen name="Login" component={Login} />
            <Stack.Screen name="Restablecer" component={RestablecerPasswd} />
            <Stack.Screen name="Registrar" component={RegistrarNewUsr} />
          </>
        ) : (
          <>
            <Stack.Screen name="Perfil" component={Perfil} />
            <Stack.Screen name="Configuraciones" component={CambiarPsswd} />
            <Stack.Screen name="Dietas" component={Dietas} />
            <Stack.Screen name="Datos" component={Data} />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
};

这是我的配置文件组件,这是我想要捕获从 http 请求获得的数据的地方,包括我用来进入此屏幕的令牌:

const Perfil = ({navigation}) => {
  return (
    <SafeAreaView>
        <ScrollView>
          <Text>Datos del Usuario</Text>
          <Button title="Configuraciones" onPress={() => navigation.navigate('Configuraciones')}/>
          <Button title="Mis Dietas" onPress={() => navigation.navigate('Dietas')}/>
          <Button title="Datos Semanales" onPress={() => navigation.navigate('Datos')}/>
        </ScrollView>
    </SafeAreaView>
  )
}

这是我在进入 Perfil 组件屏幕之前获取令牌的方式:

const Login = ({navigation}) => {
  const INITIAL_TOKEN = 0;
  const token = useState(INITIAL_TOKEN);
  const [email,setEmail] = useState('');
  const [password,setPassword] = useState('');
  const onEndGetDatos = (payload) => {
    AsyncStorage.setItem('token', payload.data.token);
  };

  const sendDataL = () => {
    Axios.post('http://3.90.64.114/api/v1/web/login',{
        email,
        password
    }
    ).then(response => {
        onEndGetDatos(response);
    }).catch(err => {
        alert(err);
    })
  }

  useEffect(() => {
    if (token !== INITIAL_TOKEN) {
      AsyncStorage.setItem('token', `${token}`);
    }
  }, [token]);

  return (
    <SafeAreaView>
        <ScrollView>
          <TextInput placeholder="Usuario(email)"
            onChangeText={email => setEmail(email)}
            keyboardType = 'email-address'
          />
          <TextInput placeholder="Contraseña" 
            secureTextEntry={true} 
            onChangeText={password => setPassword(password)}/>
          <Button title="Entrar" onPress={sendDataL}/>
          <Button title="Olvide mi Contraseña" onPress={() => navigation.navigate('Restablecer')}/>
          <Button title="Soy Nuevo" onPress={() => navigation.navigate('Registrar')}/>
        </ScrollView>
      </SafeAreaView>
  )
}

标签: react-native

解决方案


当应用首次在此处呈现时,您的应用已经从本地存储中获取令牌:

useEffect(() => {
    AsyncStorage.getItem('token').then((value) => {
      if (value) {
        setUserToken(value);
      }
    });
  }, []);

您可以设置一个状态值,例如userLoggedInto true,并且可以在整个应用程序中使用该状态值。

当您想注销时,只需清除本地存储中的令牌值并将userLoggedIn状态设置为false.

要将此值传递给子组件,您可以使用propsuseContext()挂钩。


推荐阅读