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

React Native - How to deal with asynchronism with 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)
    })      
  }

用于持久化数据。根据 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);
    }
  };

注意:持久化数据是异步过程。这就是为什么你需要使用 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);
  });