【问题标题】:Call a async function to store accessToken during authentication React-native在身份验证期间调用异步函数存储 accessToken React-native
【发布时间】:2018-02-05 16:11:30
【问题描述】:

我创建了一个 React-native 应用程序,使用 Auth0 身份验证(使用下面的身份验证代码示例):

_onLogin() {
    auth0
        .webAuth
        .authorize({scope: 'openid email', audience: 'https://' + credentials.domain + '/userinfo'})
        .then(credentials => Alert.alert(
                  'Login Success',
                  'AccessToken: ' + credentials.accessToken,
                  [
                    {text: 'OK', onPress: () => console.log('OK Pressed')},
                  ],
                  { cancelable: false },
                  Actions.home()
                ))
        .catch(error => console.log(error));
  }

并且我有这个简单的函数用于将一些值存储到 AsyncStorage 中(在这种情况下,我想存储上面函数中 credentials.accessToken 正确给出的 accessToken)。

async _storeSomeValues(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  }

我查了很多帖子,尝试了很多方法在.then(...)语句中使用这个函数,但它总是告诉我这个错误:

ReferenceError: _storeSomeValues is not defined

为什么我的函数没有在这里定义?

这是我的第一个 react-native 应用程序,我以前从未使用过 react 编码。

【问题讨论】:

  • 你在哪里打电话给_storeSomeValues
  • 我真的不知道如何将我的 _storeSomeValues 函数调用到我的 .then(...) 语句中。我尝试了很多方法来调用它,但它总是向我显示错误。
  • 我发现了问题,我只需要像箭头函数一样声明 _onLogin 函数。 _onLogin = () => { //.. } 然后我可以打电话给_storeSomeValues 喜欢this._storeSomeValues(params....)

标签: react-native auth0 asyncstorage


【解决方案1】:

如果您的_storeSomeValues 在另一个文件中,您必须将其从您的文件中导出,然后再将其导入另一个文件中。

先在file1.js

export async function _storeSomeValues(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  }

然后在你的file2.js

import { _storeSomeValues } from 'path/to/file1.js';

然后您可以在文件中的任何位置使用它。每次您想在另一个文件中使用 _storeSopeValues() 时都执行此操作。

【讨论】:

  • 我的_storeSomeValues 函数与_onLogin 函数在同一个文件中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 2022-11-25
  • 2018-03-10
  • 2017-07-12
  • 2016-12-25
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多