Reactjs 使用firebase cloud firestore进行反应-显示数据库中的数据
我正试图找出如何从我的云firestore中获取数据 我已经放弃了想办法去做这件事,我只是想去一个我在开始用钩子之前能够到达的地方 在我的旧组件DidMount中,我能够使用:Reactjs 使用firebase cloud firestore进行反应-显示数据库中的数据,reactjs,firebase,google-cloud-firestore,react-hooks,use-effect,Reactjs,Firebase,Google Cloud Firestore,React Hooks,Use Effect,我正试图找出如何从我的云firestore中获取数据 我已经放弃了想办法去做这件事,我只是想去一个我在开始用钩子之前能够到达的地方 在我的旧组件DidMount中,我能够使用: async componentDidMount() { // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config. let options = [];
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]);
这将生成我可以用来填充选择菜单的内容。选择选项在选择菜单中列出数据库的标题字段
我想了解的是,我能够在原始版本中展示select选项
即:
有人能看到如何更改从cloud firestore提取的值的表示格式吗?如果没有错误,在卸载组件时,您正在调用
unsubscribe
,因此这种方法不起作用。请参见=>
试着这样做:
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]);
你的解决方案把我列出的三个步骤缝合在一起了吗?我知道你在第一个方法中就这么做了,所以我跳过了这一部分,但如果需要,我可以帮你做。我不理解你的解决方案。感谢您的见解-但我不明白您的建议查看您的代码,当组件
卸载时,您正在调用unsubscribe()
。为澄清而编辑。Ups!!天啊。。。我没有意识到xD取消订阅
不是一个函数。。。