如何将状态传递给 firebaseConnect 中的 doc 属性
Posted
技术标签:
【中文标题】如何将状态传递给 firebaseConnect 中的 doc 属性【英文标题】:How to pass in a state to the doc property in firebaseConnect 【发布时间】:2019-10-26 23:43:23 【问题描述】:我正在创建我的第一个 React 应用程序,我需要将一个 ID 与我的 Firestore 集合中的用户 ID 相似的特定文档添加到我的应用程序状态。我正在使用 redux-firestore。有没有办法可以将变量(user_id)从状态传递到 firestoreConnect 属性
我刚开始使用 React。所以我什至不知道从哪里开始
import React, Component from "react";
import connect from "react-redux";
import firestoreConnect from "react-redux-firebase";
import compose from "redux";
class BuyDataContent extends Component
constructor(props)
super(props);
this.state =
price: "300",
check: false
;
//handlechange
handleChange = e =>
this.setState(
[e.target.name]: e.target.value
);
;
//This method handles a submit of the form
handleSubmit = e =>
e.preventDefault();
this.setState( check: true );
;
render()
console.log(this.props);
return (
<div className="row">
<div className="col-lg-10">
<div className=" card card-white">
<div className="card-header">
<div className="panel panel-default text-center">
<div className="panel-body">
<form onSubmit=this.handleSubmit>
<div className="form-group">
<label for="plan">Select Amount</label>
<select
name="price"
className="form-control form-control-lg"
onChange=this.handleChange
>
<option value="1500"> 1500</option>
</select>
</div>
<input
type="submit"
className="btn btn-primary"
value="Buy"
/>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
const mapStateToProps = state =>
console.log(state);
return
USERID:state.firebase.auth.uid
;
;
const mapDispatchToProps = dispatch =>
return
buyData: detail => dispatch(buyData(detail))
;
;
//export
```
export default compose( connect( mapStateToProps, mapDispatchToProps), firestoreConnect([ collection: "users", doc: USERID ])
)(BuyDataContent);
```
关于如何将每个用户的用户 ID 传递给 firestoreConnect“doc”属性并从用户集合中获取特定文档的任何想法。用户 ID 存在于我的应用程序状态中。
【问题讨论】:
【参考方案1】:您可以像这样在组件中使用useFirestoreConnect
:
import useFirestoreConnect from 'react-redux-firebase';
class BuyDataContent extends Component
constructor(props);
super(props);
const USERID = props; // get user id coming from mapStateToProps
useFirestoreConnect([
collection: 'users',
doc: USERID ,
storeAs: 'user', // indicate the response to be stored in a "user" property inside props
,
]);
const user = props; // get firestore response from "user" property
if (isEmpty(user))
... // check if the user is not loaded from firestore yet
// perform actions when user is loaded
...
同时从compose
中删除firestoreConnect
。
这应该可行,请查看文档以供参考:https://react-redux-firebase.com/docs/api/useFirestoreConnect.html#examples
【讨论】:
太棒了!现在看起来好多了:)以上是关于如何将状态传递给 firebaseConnect 中的 doc 属性的主要内容,如果未能解决你的问题,请参考以下文章