Mel*_*Mel 6 firebase reactjs react-hooks
我试图弄清楚如何在我的 React 应用程序中使用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
});
}
Run Code Online (Sandbox Code Playgroud)
我现在正在尝试学习如何使用钩子从使用 react-firebase-hooks 的数据库中获取数据。我目前的尝试是:
import { useDocumentOnce } from 'react-firebase-hooks/firestore';
Run Code Online (Sandbox Code Playgroud)
我也试过 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
}),
);
Run Code Online (Sandbox Code Playgroud)
这会生成一个错误,指出:'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,
})},
);
Run Code Online (Sandbox Code Playgroud)
如何从 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}
/>
Run Code Online (Sandbox Code Playgroud)
作为参考,我的表单中有 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"});
}, []);
Run Code Online (Sandbox Code Playgroud)
如何从数据库查询添加快照?
我曾尝试为快照制作类似的 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 });
};
Run Code Online (Sandbox Code Playgroud)
但它不起作用。错误消息说:
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()
})
Run Code Online (Sandbox Code Playgroud)
这也不起作用 - 它会产生一条错误消息,内容为:
类型错误: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,
})},
);
Run Code Online (Sandbox Code Playgroud)
这也是不正确的。错误消息指向 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
});
});
});
Run Code Online (Sandbox Code Playgroud)
错误消息说:TypeError: _firebase__WEBPACK_IMPORTED_MODULE_5__.firebase.firestore.collection is not a function
下一个尝试
const searchFieldOfResearchesOptions = (searchKey, resolver) => {
// for more info
// /sf/ask/2703326741/
// 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);
};
Run Code Online (Sandbox Code Playgroud)
这种尝试实际上可以从数据库中检索数据(万岁) - 除非我无法获得我想要呈现的文本标签。集合中的每个文档都有 2 个字段。第一个是标题,第二个是id号,我的最后一步是制作一个插入文本的标签(即ABS - ),然后将id号和标题放在一起。
我添加了注释代码以显示提取每个文档标题的方法,但是我尝试按照我想要的方式制作标签的额外部分不会出现错误,它只是不起作用 - 我仍然只得到列表中的文档标题。
有谁知道如何使用钩子从云 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>
);
};
Run Code Online (Sandbox Code Playgroud)
您可以像示例中那样使用 useDocument,但也可以选择使用 useDocumentOnce。但在这种情况下,请相应地更改导入(以import { useDocumentOnce } from 'react-firebase-hooks/firestore';
归档时间: |
|
查看次数: |
5363 次 |
最近记录: |