繁体   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