redux - 使用 react-redux-firebase 将组件连接到 redux 时选择 firestore 子集合
问题描述
我在我的 react-native 移动应用程序中使用带有屏幕react-redux-firebase
的中间件。fireStoreConnect()
在将组件连接到 redux 商店时,我想指定我连接到的 firestore 子集合,这取决于正在导航应用程序的用户。
我应该如何指定集合firestoreConnect
?用户 ID 在 redux 存储中。
MWE:
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>
</View>
);
}
}
const mapStateToProps = (state) => {
// reference the subcollection of the user
const images = state.firestore.data.images;
return {
images: images,
}
}
export default compose(
firestoreConnect([
{
collection: 'users',
doc: "HOW DO I GET THE USERS ID HERE? IT IS IN REDUX STORE",
subcollections: [{ collection: 'images' }]
}
]),
connect(mapStateToProps),
)(PhotosScreen)
解决方案
Firestore(和所有 NoSQL 数据库)遵循交替的“ (父)集合/文档/集合/文档......”分层模式。要将 React 组件与父 firestore 集合下的子集合和文档同步,您需要将子集合/子文档层次结构信息作为 props 传递给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)
推荐阅读
- javascript - 比较两个字符串的时间差(JS)
- javascript - 单击图像时如何从数组中检索图像详细信息
- java - 如何定义一个具有泛型参数的类,该类扩展了具有泛型参数的类?
- python - 将数据从一个文件逐行写入另一文件
- c++ - C++:为什么我必须以这种方式将我的声明定为双精度?
- parsing - 如何在 Haskell 中解析浮点数(Parsec.Combinator)
- android - 2020年Android Slices的现状如何
- laravel - Artisan 无法连接到容器中的作曲家
- r - RcppArmadillo:C 函数 'SEXPREC* sourceCpp_1_hh(SEXP, SEXP, SEXP)' 的声明冲突
- acumatica - 如何添加到自定义图形活动按钮?