簡體   English   中英

React Native AsyncStorage 異步函數返回

[英]React Native AsyncStorage async function return

我有一個輔助功能:

export async function isFavorite(id) {
  try {
    let favorites = await AsyncStorage.getItem("@rn-food-app:favorites");
    if (favorites) {
      return JSON.parse(favorites).includes(id);
    }
    return false;
  } catch (error) {
    return false;
  }
}

我這樣稱呼它:

class DetailScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      recipe: null,
      isFavorite: false,
    };
  }

  componentDidMount() {
    const { route } = this.props;

    if (route.params && route.params.recipeId) {
      const recipe = getRecipe(route.params.recipeId);
      this.setState(
        {
          recipe,
        },
        () => {
          this.checkIfFavorite();
        }
      );
    }
  }

  checkIfFavorite() {
    const { recipe } = this.state;

    console.log(isFavorite(recipe.id));
  }

... ... ...

但是console.log()返回這樣的東西

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

而不是bool

我可以讓它像這樣工作:

export async function isFavorite(id) {
  try {
    return await AsyncStorage.getItem("@rn-food-app:favorites");
  } catch (error) {
    return false;
  }
}

然后在DetailScreen component

  checkIfFavorite() {
    const { recipe } = this.state;

    isFavorite(recipe.id)
      .then((res) => {
        const favorite = JSON.parse(res).includes(recipe.id);
        console.log(favorite);
      })
      .catch((err) => console.log(err));
  }

這有效,但為什么上述方法無效? 我想將所有這些邏輯提取到一個輔助函數中,這樣我就可以在我的組件中簡單地調用isFavorite: bool而無需額外的邏輯。

看起來你沒有正確地解決你的承諾,這就是為什么你看起來很奇怪 console.log

看看這個例子並根據你的需要改變它 - 當從 AsyncStorage 獲取項目時,我正在調用 2x .then() 調用和 1x .catch() 調用。

您可以使用 AsyncStorage 像這樣存儲和檢索數據:

  const storeData = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value); 
    } catch (error) {
      console.log(error);
    }
  };

  const getData = async key => {
    try {
      const data = await AsyncStorage.getItem(key);
      if (data !== null) {
        console.log(data);
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  };

然后使用鍵名調用 getData 就像您將值存儲在任何您想要的位置並將鍵設置為狀態值一樣。

存儲值:

storeData("@rn-food-app:favorites", the value);

獲取值:

  await getData"@rn-food-app:favorites") 
    .then((data) => data)
    .then((value) => this.setState({ isFavorite: value }))
    .catch((err) => console.log("AsyncStorageErr: " + err));

您正在注銷 Promise 而不是 Promise 的實際結果,如下所示:

 async checkIfFavorite() {
    const { recipe } = this.state;
    const isFav = await isFavorite(recipe.id) 

    console.log(isFav);
  }

或者沿着這些路線的東西會起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM