【问题标题】:How to get multiple data from firebase just with unique keys in react-native如何仅使用 react-native 中的唯一键从 firebase 获取多个数据
【发布时间】:2018-06-01 20:14:44
【问题描述】:

我在从 firebase 特定位置检索数据时遇到问题。我有一个状态(取自 firebase 的“收藏夹”)。收藏夹状态对象仅包含在单击“发布添加到收藏夹”时推送的唯一 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>
    );
  }
}

【问题讨论】:

  • 你的代码和数据结构是什么?
  • 嗨 Benthanx 回复。添加了我的代码
  • @Ben 你能帮忙吗?

标签: javascript firebase react-native firebase-realtime-database


【解决方案1】:

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
  })
})

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多