我试图弄清楚如何从我的云Firestore中获取数据。
我已经放弃尝试解决如何使用react-firestore-hook的方法,而只是想尝试使用钩子之前到达的位置。
在旧的componentDidMount中,我可以使用以下代码:
async componentDidMount() {
// const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
let options = [];
await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
options.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
});
});
});
this.setState({
options
});
现在,我能做的最好的事情是:
useEffect(() => {
// fetch data
const unsubscribe = fsDB
.collection("abs_for_codes")
.onSnapshot(({ docs }) => {
setFieldOfResearchesOptions(
// map data to react-select
docs.map(doc => {
const { title } = doc.data();
return {
value: doc.id,
label: title
};
})
);
}, setFieldOfResearchesError);
return () => unsubscribe();
}, [setFieldOfResearchesError, setFieldOfResearchesOptions]);
这将生成可用于填充选择菜单的内容。选择选项在选择菜单中列出数据库的标题字段。
我试图达到的目的是能够在原始版本中展示选择选项。
那是:
在每个值的开头插入一个字符串,例如“ ABS-”
在该字符串后插入每个文档的文档ID
然后插入标题。
我已经在旧的componentDidMount中工作了。
我找不到在当前尝试中将其集成的方法。
谁能看到如何更改从Cloud Firestore提取的值的表示格式?
如果没有弄错,则unsubscribe
在组件卸载时正在调用,因此这种方式将不起作用。参见=> https://reactjs.org/docs/hooks-reference.html#useeffect
像这样尝试:
useEffect(() => {
let options = [];
await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
options.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
});
});
setFieldOfResearchesOptions(options);
});
}, [setFieldOfResearchesError, setFieldOfResearchesOptions]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句