【问题标题】:React Native - How to deal with asynchronism with AsyncStorageReact Native - 如何使用 AsyncStorage 处理异步
【发布时间】:2020-08-22 13:24:36
【问题描述】:

我正面临异步问题:

  1. 我在 firebase 中创建了一个用户,并为其生成了一个唯一 ID。
  2. 我得到了这个唯一的 ID。
  3. 我调用了一个异步函数来使用 AsyncStorage 方法保存此 ID。

问题:在我从用户创建中取回生成的 ID 之前调用了 asyncStorage 方法。如何处理?

这是我的代码:

class Subscription extends Component {

  constructor() {
    super();
    this.state = {
      email: '', 
      password: ''
    }
  }

  persistUserId = (userID) => {
    try {
      AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
    } catch (error) {
      console.log(error.message);
    }
  };

  updateInputValue = (value, prop) => {
    const state = this.state;
    state[prop] = value;
    this.setState(state);
  }

  registerUser = () => {
    var generatedUserId = '';

    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
    .then((res) => {
        var user = { // Set Javascript Object to insert
        email: this.state.email
        }

        database.collection("users").add({ // Create the new user generating an ID
            'email': user.email,
        }).then(function(docRef) {
            generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
        }).then(function() {
            this.persistUserId(generatedUserId) // Call the AsyncStorage to persist the ID
        })
            this.props.navigation.navigate('AppPage') // Go to next page.
    })
    .catch(error => {
        alert(error.message)
    })      
  }

【问题讨论】:

    标签: javascript reactjs react-native asyncstorage asynchronous-javascript


    【解决方案1】:

    用于持久化数据。根据 react-native 文档。您需要使用 async await 关键字:

    _storeData = async () => {
      try {
        await AsyncStorage.setItem(
          '@MySuperStore:key',
          'I like to save it.'
        );
      } catch (error) {
        // Error saving data
      }
    }
    

    你的情况:

    persistUserId = async (userID) => {
        try {
          await AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
        } catch (error) {
          console.log(error.message);
        }
      };
    
    

    注意:持久化数据是异步过程。这就是你需要使用异步等待的原因

    您需要更新您的 Firebase,然后再进行捕获。使用 bind 或使用 arrow 功能。这是更新版本:

    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
      .then((res) => {
        var user = {
          // Set Javascript Object to insert
          email: this.state.email,
        };
    
        database
          .collection("users")
          .add({
            // Create the new user generating an ID
            email: user.email,
          })
          .then( (docRef) =>  {
            generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
          })
          .then( () =>  {
            this.persistUserId(generatedUserId); // Call the AsyncStorage to persist the ID
          });
        this.props.navigation.navigate("AppPage"); // Go to next page.
      })
      .catch((error) => {
        alert(error.message);
      });
    

    【讨论】:

    • 我收到此错误:可能未处理的承诺拒绝。 TypeError: undefined is not an object(评估 this.persistUserId)。
    • 不确定。检查您的错误对象。很有可能没有 message 字段
    • 我在没有“try catch”的情况下检查它,同样的错误。这就像方法 persistUserId 永远不会启动...
    • 啊,因为你正在使用函数。所以它没有得到这个范围。更好的方法是包装箭头函数
    • 哇,这很棘手!坦克很多!你让我开心!!
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 2015-08-12
    • 2018-10-16
    • 2021-06-25
    • 2019-08-03
    • 2019-03-21
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多