React Native-如何使用AsyncStorage处理异步问题

问题描述

我正面临异步问题:

  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)
    })      
  }

解决方法

用于保留数据。根据反应本地文档。您需要使用 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);
    }
  };

注意:持久数据是异步过程。这就是为什么您需要使用async await

您需要更新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);
  });