【发布时间】:2020-03-07 21:08:03
【问题描述】:
我正在尝试弄清楚如何在我的 react 应用程序中使用 react-firebase-hooks,以便简化对数据库的调用。
我之前的版本(在 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
});
}
我现在正在尝试学习如何使用钩子通过 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' is not defined
我试过了(这也是不正确的):
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 注册语句,如下所示:
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()
})
这也不起作用 - 它会产生一条错误消息:
TypeError: 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 集合中生成一组选择菜单选项?
【问题讨论】:
-
明天我将获得新的赏金以尝试获得解决此问题的帮助 - 我仍在尝试弄清楚如何使用 firebase
标签: reactjs firebase react-hooks