使用react-redux-firebase

时间:2019-02-16 19:06:38

标签: redux react-redux google-cloud-firestore react-redux-firebase

我正在将react-redux-firebase的{​​{1}}中间件与 我的本机移动应用程序中的屏幕。在将组件连接到redux存储时,我想指定我连接的firestore子集合,这取决于正在浏览应用程序的用户。

如何在fireStoreConnect()中指定集合?用户ID位于redux存储中。

MWE:

firestoreConnect

2 个答案:

答案 0 :(得分:3)

Firestore(和所有NoSQL数据库)遵循交替的“ (父)集合/文档/集合/文档...”分层模式。要将React组件与父级Firestore集合下的子集合和文档同步,您需要将子集合/子文档层次结构信息作为道具传递给 firestoreConnect

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { compose } from 'redux';
import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase';

class PhotosScreen extends Component {
  render() {
    return (
      <View>
        <Text> i plan the use this.props.images here </Text>
        {images && images.length ? <div> render your images here using this.props.images and images.map </div> : <p>No images</p>}
      </View>
    );
  }
}

const mapStateToProps = (state) => {


    return {
        images  : state.firestore.data.images, // reference the subcollection of the user
        userId  : state.firestore.auth.uid     // assuming the 'doc id' is the same as the user's uid
    }                                          
}

export default compose(
    firestoreConnect((props) => 

        if (!props.userId) return []                 // sync only if the userId is available (in this case, if they are authenticated)
        return [
            {
               collection     : 'users',             // parent collection
               doc            : props.userId,        // sub-document
               subcollections : [
                      {collection : 'images'}        // sub-collection
               ],
               storeAs        : 'images'
            }
         ]
    }),
    connect(mapStateToProps),
)(PhotosScreen)

答案 1 :(得分:1)

在1.x版

const enhance = compose(
  connect(
    (state) => ({
      someKey: state.someData
    })
  ),
  firebaseConnect(
    (props, firebaseInstance) => [
      { path: `${props.someKey}/someData` }
    ]
  )
)

在2.x版

firebaseConnect(
  (props, store) => [
    { path: `${store.getState().someKey}/someData` }
  ]
)

请注意firebaseConnect中的第二个参数如何从firebaseInstance变为store,从v1变为v2。

这应该可以满足您的需求。