我想从Firestore子集合中获取名为settings
的文档,然后将其作为变量settings
加载到我的本地组件(和Redux存储)中,并具有以下值:
settings: {
name: 'Waldo Garply',
email: 'corge@foogle.net',
mobile: '555-789-1234',
timestamp: '1546304499032',
}
相反,我的应用无法编译,并且在控制台中收到以下错误消息:
控制台错误未捕获到的TypeError:无法读取Function.mapStateToProps上未定义的属性“设置”(作为mapToProps)
我在做错什么,如何实现预期的行为?
我正在按以下方式存储我的Firestore数据。
消防处.
├── users
| ├── OGk02kJbQUesTeVhTrLBnERSxrfm
| | ├── settings
| | | ├── VrxDnSxpUw6wgX0n9c1FbapmLaLa
| | | | ├── name: Waldo Garply
| | | | └── timestamp: 1546304499030
| | | ├── cGVHxSkU3Lcb9WAYWjnJKcLOTYf8
| | | | ├── name: Waldo Garply
| | | | ├── email: corge@foogle.net
| | | | └── timestamp: 1546304499031
| | | ├── qoDYG2xloEvUUhGQyF9zXy9MTMIq
| | | | ├── name: Waldo Garply
| | | | ├── email: corge@foogle.net
| | | | ├── mobile: 555-789-1234
| | | | └── timestamp: 1546304499032
注意,每次任何设置值更改时,我都会存储所有设置值(包括时间戳记)的唯一快照;然后,我获取最新设置(按时间戳排序)并加载它。因此,我需要在settings
对象上使用自动侦听器。
我正在组件中使用以下代码(称为DetailsTab.js)尝试连接到Firestore以获取数据,然后将其作为settings
变量加载到组件和Redux存储中。
function mapStateToProps( state ) {
console.log('state\n', state);
return {
user: state.auth.user,
// attempted all the following individually
settings: state.firestore.data.users.settings, // throws error
settings: state.firestore.ordered.users.settings, // throws error
settings: state.firestore.ordered.users[0] // throws error
settings: state.firestore.ordered.users // returns 'users' object
}
}
export default compose(
withStyles(styles, { withTheme: true }),
connect(mapStateToProps, mapDispatchToProps),
firestoreConnect(props => {
return [
{
collection: 'users',
doc: props.user.data.uid,
subcollections: [
{
collection: 'settings',
limit: 1,
orderBy: ['timestamp', 'desc',],
storeAs: 'settings',
},
],
},
];
})
)(DetailsTab)
以下是我的控制台记录数据时的数据显示方式。
console.logstate
└── firestore
├── data
| └── users
| └── OGk02kJbQUesTeVhTrLBnERSxrfm
| └── settings
| └── qoDYG2xloEvUUhGQyF9zXy9MTMIq
| ├── name: Waldo Garply
| ├── email: corge@foogle.net
| ├── mobile: 555-789-1234
| └── timestamp: 1546304499032
├── ordered
| └── users [Array(1)]
| └── 0
| ├── id: OGk02kJbQUesTeVhTrLBnERSxrfm
| └── settings [Array(1)]
| └── 0
| ├── id: qoDYG2xloEvUUhGQyF9zXy9MTMIq
| ├── name: Waldo Garply
| ├── email: corge@foogle.net
| ├── mobile: 555-789-1234
| └── timestamp: 1546304499032
答案 0 :(得分:0)
解决方案是按如下所示添加适当的错误防护。
function mapStateToProps( state ) {
console.log('state\n', state);
const settings = state.firestore.ordered.users
&& state.firestore.ordered.users[0]
&& state.firestore.ordered.users[0].settings
&& state.firestore.ordered.users[0].settings[0];
return {
user: state.auth.user,
settings,
}
}