使用 AsyncStorage 在 React Native 中添加到收藏夹/喜欢不起作用?

Add to favorites/ likes in React Native using AsyncStorage not working?

我一直致力于添加到收藏夹功能。 基本上,我有两个图标图像,一个是白色背景的心形,另一个是 red-background 心形。 我的 Objects 是房子。每个房子只能用一个 houseNumber 表示,它是由数字和字母(字母数字)组成的字符串。

当加载特定房屋的视图时,我想检查当前房屋编号是否已保存在收藏夹 (asyncStorage) 中。如果是,则显示红色。如果不在收藏夹中,则empty-colored心显示

这是我的 _updateList 方法,它在组件安装时调用:

async _updateList() {
   const response = await AsyncStorage.getItem('listOflikes');
   const listOfLikes = await JSON.parse(response) || [];
   this.setState({
       favorites: listOfLikes
     });
   console.log(this.state.favorites);
   if (listOfLikes.includes(this.props.houseNumber)) {
     this.setState({ isLiked: true });
   }
   else {
     this.setState({ isLiked: false })
   }
   console.log(this.state.isLiked);
 }

在 componentDidMount 上,调用了 _updateList:

componentDidMount() {
    console.log(this.props.houseNumber);
    console.log(this.props.latitude);
    console.log(this.props.longitude);
    this._updateList();
 }

目前还没有房子被添加到收藏夹。当我点击心形图像时,我目前希望显示红色心形,并在 asyncStorage 中添加当前门牌号。但是,收藏夹仍然是一个空数组,显示 empty-colored 听到的图像。 以下是其余功能:

async _addToFavorites() {
    const listOfHouses = [...this.state.favorites, this.props.houseNumber];

    await AsyncStorage.setItem('favorites',
    JSON.stringify(listOfHouses));
    this._updateList();
  }

 _onPressHeartButton() {
      if(this.state.isLiked){
    // remove from favorites
    }
   else{
    // add to favorites
    this._addToFavorites();
   }
  }

renderHeart() {
  if (this.state.isLiked) {
    return (
      <Image
        source={require('./images/ic_like_pressed.png')}
         style={{
           width: '50%',
           height: '50%',
           alignItems: 'flex-end',
           alignSelf: 'center',
           marginTop: 0,
           resizeMode: 'contain',
           marginBottom: 0,
           paddingBottom: 0,
           marginLeft: '20%'
         }}
      />
          );
  }
  else {
    return (
      <Image
        source={require('./images/ic_like_normal.png')}
         style={{
           width: '50%',
           height: '50%',
           alignItems: 'flex-end',
           alignSelf: 'center',
           marginTop: 0,
           resizeMode: 'contain',
           marginBottom: 0,
           paddingBottom: 0,
           marginLeft: '20%'
         }}
      />
    );
  }
}

心在视图中是这样显示的:

<TouchableWithoutFeedback onPress={this._onPressHeartButton.bind(this)} >
   {this.renderHeart()}
</TouchableWithoutFeedback>

您遇到的问题与 setState 异步有关。您需要将逻辑放在 setState 回调中。您可以阅读更多内容 here

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

示例 (未测试)

async _updateList() {
  const response = await AsyncStorage.getItem('listOflikes');
  const listOfLikes = await JSON.parse(response) || [];
  this.setState({
    favorites: listOfLikes
  }, () = > {
    console.log(this.state.favorites);
    if (listOfLikes.includes(this.props.houseNumber)) {
      this.setState({
        isLiked: true
      });
    }
    else {
      this.setState({
        isLiked: false
      })
    }
    console.log(this.state.isLiked);
  });
}

您正在使用两个不同的密钥来访问 AsyncStorage 实例("favorites" 和 "listOfLikes")。您必须在两个地方使用相同的密钥。