reactjs - React-firestore-hooks 从云 Firestore 中获取数据库记录
问题描述
我试图弄清楚如何在我的反应应用程序中使用react-firebase-hooks,以便我可以简化对数据库的调用。
我之前的版本(在这个问题上的帮助下解决了)这个尝试使用了这个类组件和一个 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
});
}
我现在正在尝试学习如何使用钩子使用 react-firebase-hooks 从数据库中获取数据。我目前的尝试是:
import { useDocumentOnce } from 'react-firebase-hooks/firestore';
我也试过 import { useDocument } from 'react-firebase-hooks/firestore';
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 是手动定义的,但建立它们的值的过程如下:
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 register 语句,如下所示:
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:初始化前无法访问“快照”
我找不到如何使用数据库中的数据填充选择菜单的示例。
下一次尝试
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()
})
这也不起作用 - 它会产生一条错误消息,内容为:
类型错误:fields.data 不是函数
下一次尝试
认识到我需要搜索集合而不是调用文档,但仍然不确定 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 行并显示: Parsing error: Unexpected token, expected ","
在我的收藏中,我有许多文件。每个都有 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 is not a function
下一个尝试
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 号和标题放在一起。
我添加了注释代码以显示提取每个文档标题的方法,但是我尝试按照我想要的方式制作标签的额外部分不会出现错误,它只是不起作用 - 我仍然只得到列表中的文档标题。
有谁知道如何使用钩子从 Cloud Firestore 集合中生成一组选择菜单选项?
解决方案
从 'react-firebase-hooks/firestore' 导入 { useDocument };
为什么 ?你用的是useDocumentOnce,当然需要导入这个函数,没有useDocument,你不用。
最后一个错误:您甚至在初始化之前就使用了 const,因此
ReferenceError:初始化前无法访问“快照”
快照将由 useDocumentOnce 初始化,您不能将其(快照)用作传递给将要对其进行初始化的函数的参数。
另外,我查看了 react-firebase-hooks,这里是useDocumentOnce的文档:
使用此示例,并对其进行调整以使用您要使用的文档。
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';
推荐阅读
- python - 多线程行搜索
- c# - 我收到此错误消息`ContextSwitchDeadlock`
- postman - 纽曼:发送另一个请求而不等待答案
- python - 将JSON中的所有元素获取到python中的列表中
- javascript - 从顶级 App 类更改 React 上下文
- python - 将行从一个数据帧添加到另一个
- php - ErrorException(E_ERROR)试图在laravel 5.8中获取非对象的属性'id'
- java - 使用 Paulscode 播放 .ogg 文件格式时 ChannelJava Sound 类出错
- javers - Javers 演示项目坏了?
- c# - 尝试查找给定深度嵌套的类/对象的属性名称