如何使用react-native中的唯一键从firebase获取多个数据

问题描述 投票:1回答:1

我在从firebase特定位置检索数据时遇到问题。我有一个州(“收藏夹”取自火柴)。收藏夹状态对象仅包含在单击“post add to favorites”时推送的唯一firebase密钥(我在firebase中发布了数据)。那么,我如何使用“收藏夹”节点中的唯一键检索多个帖子数据?

码:

class MyFavouriteScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      favourites: [],
      favouritesPosts: [],
    };
  }

  componentWillMount() {
    let user = firebase.auth().currentUser.uid;
    favouritesFire = firebase.database().ref('users').child(user + '/favourites');

    let that = this;
    favouritesFire.once("value", function(snapshot){
      let favs = [];
      snapshot.forEach(function(data){
        let fav = {
            id: data.key
        }
        favs.push(fav);
        that.setState({favourites: favs});
      });
    });
    // ^- there i get those unique keys and now i need to retrieve post data with those keys and show them in render function
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.mainContainer}>
        <MyNavScreen banner="Favoritai" navigation={ navigate } />
        <ScrollView style={styles.wrapper}>
      {this.state.favouritesPosts.map(post => {
        return (
          <TouchableOpacity post={post} style={styles.postWrapper}>
            <View style={styles.postImageWrapper}>
              <Image
                source={{uri: post.image}}
                style={{flex: 1}} />
            </View>
            <View style={styles.shopContent}>
              <Text style={styles.postTitle}>{post.title}</Text>
              <Text style={styles.postText}>{post.text}</Text>
            </View>
            <TouchableOpacity style={styles.starWrapper}>
              <Text style={styles.star}>{'-'}</Text>
            </TouchableOpacity>
          </TouchableOpacity>
        );
      })}
        </ScrollView>
      </View>
    );
  }
}
javascript firebase react-native firebase-realtime-database
1个回答
0
投票

Firebase不太适合处理查询。我建议你这样的事情

favouritesFire.once("value", snapshot => {
  snapshot.map(item => { // it will pass through all your snapshot items
    firebase.database().ref(`yournode/${item.key}`) //for each item you must query again in firebase
    .once('value')
    .then(itemFiltered => console.log('Your item: ', itemFiltered); // then you get your result
  })
})

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.