我正在尝试弄清楚如何使用 react-firebase-hooks在我的 React 应用程序中,以便我可以简化对数据库的调用。
我之前的版本(在 this question 的帮助下解决)使用了带有 componentDidMount 函数的此类组件(它有效):
class Form extends React.Component {
state = {
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
});
}
我现在正在尝试学习如何使用钩子(Hook)通过react-firebase-hooks从数据库中获取数据。我目前的尝试是:
import { useDocumentOnce } from 'react-firebase-hooks/firestore';
我也尝试过 从 'react-firebase-hooks/firestore' 导入 { useDocument };
const [snapshot, loading, error] = useDocumentOnce(
firebase.firestore().collection('abs_for_codes'),
options.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
}),
);
这会生成一个错误:“useDocumentOnce”未定义
我尝试过(这也是不正确的):
const [snapshot, loading, error] = useDocumentOnce(
firebase.firestore().collection('abs_for_codes'),
{snapshot.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id,
})},
);
如何从 firebase 获取集合?我正在尝试使用从 Firebase 中名为“abs_for_codes”的集合中读取的选项来填充选择菜单。
我认为 useState 的重点是我不需要再声明状态,我可以直接调用 我在下面添加了我的选择尝试:
<Select
className="reactSelect"
name="field"
placeholder="Select at least one"
value={valuesSnapshot.selectedOption}
options={snapshot}
onChange={handleMultiChangeSnapshot}
isMulti
ref={register}
/>
作为引用,我的表单中有另外 2 个选择菜单。我用来设置这些选项的常量是手动定义的,但建立它们值的过程如下:
const GeneralTest = props => {
const { register, handleSubmit, setValue, errors, reset } = useForm();
const { action } = useStateMachine(updateAction);
const onSubit = data => {
action(data);
props.history.push("./ProposalMethod");
};
const [valuesStudyType, setStudyType] = useState({
selectedOptionStudyType: []
});
const [valuesFundingBody, setFundingBody] = useState({
selectedOptionFundingBody: []
});
const handleMultiChangeStudyType = selectedOption => {
setValue("studyType", selectedOption);
setStudyType({ selectedOption });
};
const handleMultiChangeFundingBody = selectedOption => {
setValue("fundingBody", selectedOption);
setFundingBody({ selectedOption });
};
useEffect(() => {
register({ name: "studyType" });
register({name: "fundingBody"});
}, []);
如何从数据库查询中添加快照?
我尝试为快照制作类似的handleMultiChange const 和 useEffect 寄存器语句,如下所示:
const [snapshot, loading, error] = useDocumentOnce(
firebase.firestore().collection('abs_for_codes'),
snapshot.push({
value: snapshot.data().title.replace(/( )/g, ''),
label: snapshot.data().title + ' - ABS ' + snapshot.id
}),
);
const [valuesField, setField ] = useState({
selectedOptionField: []
});
const handleMultiChangeField = selectedOption => {
setValue("field", selectedOption);
setField({ selectedOption });
};
但它不起作用。错误消息显示:
ReferenceError: Cannot access 'snapshot' before initialization
我找不到如何使用数据库中的数据填充选择菜单的示例。
下一次尝试
useEffect(
() => {
const unsubscribe = firebase
.firestore()
.collection('abs_for_codes')
.onSnapshot(
snapshot => {
const fields = []
snapshot.forEach(doc => {
fields.push({
value: fields.data().title.replace(/( )/g, ''),
label: fields.data().title + ' - ABS ' + fields.id
})
})
setLoading(false)
setFields(fields)
},
err => {
setError(err)
}
)
return () => unsubscribe()
})
这也不起作用 - 它会产生一条错误消息:
TypeError: fields.data is not a function
下一次尝试
认识到我需要搜索集合而不是调用文档,但仍然不确定 useCollectionData 是否比 useCollectionOnce 更合适(我无法理解有关 useCollectionData 提供的内容的文档),我现在尝试了:
const [value, loading, error] = useCollectionOnce(
firebase.firestore().collection('abs_for_codes'),
{getOptions({
firebase.firestore.getOptions:
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id,
})},
);
这也是不正确的。错误消息指向 getOptions 行并显示:解析错误:意外的标记,预期为“,”
在我的收藏中,我有很多文档。每个都有 2 个属性,一个数字和一个文本字符串。我的选项是设置数字和文本字符串的格式,以便它们以及我作为文本插入的首字母缩略词一起出现(就像我能够使用 componentDidMount 所做的那样)。
下一次尝试
我接下来尝试了这个:
const fields = firebase.firestore.collection("abs_for_codes").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
fields.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
});
});
});
错误消息显示:TypeError: _firebase__WEBPACK_IMPORTED_MODULE_5__.firebase.firestore.collection 不是函数
下一次尝试
const searchFieldOfResearchesOptions = (searchKey, resolver) => {
// for more info
// https://stackoverflow.com/questions/38618953/how-to-do-a-simple-search-in-string-in-firebase-database
// https://firebase.google.com/docs/database/rest/retrieve-data#range-queries
fsDB
.collection("abs_for_codes")
.orderBy("title")
// search by key
.startAt(searchKey)
.endAt(searchKey + "\uf8ff")
.onSnapshot(({ docs }) => {
// map data to react-select
resolver(
docs.map(doc => {
const { title } = doc.data();
return {
// value: doc.id,
// label: title
value: title.data().title.replace(/( )/g, ''),
label: title.data().title + ' - ABS ' + title.id
};
})
);
}, setFieldOfResearchesError);
};
这种尝试实际上可以从数据库中检索数据(万岁)-除了我无法获取我想要呈现的文本标签。集合中的每个文档都有 2 个字段。第一个是标题,第二个是 ID 号,我的最后一步是制作一个插入文本(即 ABS - )的标签,然后将 ID 号和标题放在一起。
我添加了注释代码来显示提取每个文档标题的有效方法,但是我尝试按照我想要的方式制作标签的额外位不会出现错误,它只是不起作用 - 我仍然只获取列表中的文档标题。
有谁知道如何使用 Hook 从云 Firestore 集合中生成选择菜单选项集?
最佳答案
import { useDocument } from 'react-firebase-hooks/firestore';
为什么?你用的是useDocumentOnce,当然需要导入这个函数,而不是useDocument,你不用。
最后一个错误:您在初始化之前就使用了 const,因此
ReferenceError: Cannot access 'snapshot' before initialization
快照将由 useDocumentOnce 初始化,您不能将它(快照)用作传递给要初始化它的函数的参数。
另外,我查看了react-firebase-hooks,这里是 useDocumentOnce 的文档:
使用this示例,并对其进行调整以使用您想要使用的文档。
import { useDocument } from 'react-firebase-hooks/firestore';
const FirestoreDocument = () => {
const [value, loading, error] = useDocument(
firebase.firestore().doc('hooks/nBShXiRGFAhuiPfBaGpt'),
{
snapshotListenOptions: { includeMetadataChanges: true },
}
);
return (
<div>
<p>
{error && <strong>Error: {JSON.stringify(error)}</strong>}
{loading && <span>Document: Loading...</span>}
{value && <span>Document: {JSON.stringify(value.data())}</span>}
</p>
</div>
);
};
您可以像示例中那样使用 useDocument,但也可以选择使用 useDocumentOnce。但在这种情况下,请相应地更改导入(至 import { useDocumentOnce } from 'react-firebase-hooks/firestore';
😏
关于reactjs - React-firestore-hooks 从云 firestore 获取数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813897/