我正在努力弄清楚如何在我的react应用程序中使用反应-火源-钩,这样我就可以简化数据库中的调用。
我以前的版本(在这个问题上帮助解决)使用了这个类组件和一个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-钩子。我目前的尝试是:
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,
  })},
);我怎么才能从火炉里得到一个收藏呢?我正在尝试填充一个select菜单,其中包含从一个名为abs_for_codes的防火墙集合中读取的选项。
我认为useState的要点是我不再需要声明一个状态,我只需要调用我在下面添加了我的选择尝试:
<Select 
            className="reactSelect"
            name="field"
            placeholder="Select at least one"
            value={valuesSnapshot.selectedOption}
            options={snapshot}
            onChange={handleMultiChangeSnapshot}
            isMulti
            ref={register}
          />供参考,我有两个其他的选择菜单在我的形式。我用来设置这些选项的consts是手动定义的,但是建立它们的值的过程如下:
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:无法在初始化前访问“快照”
我找不到如何用数据库中的数据填充select菜单的示例。
下一次尝试
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行,并指出:解析错误:意外令牌,预期",
在我的收藏中,我有许多文件。每个属性都有两个属性,一个数字和一个文本字符串。我的选项是格式化数字和文本字符串,以便它们一起出现,以及我插入的缩略词(就像我使用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
    });
    });
});错误消息是:_firebase__WEBPACK_IMPORTED_MODULE_5__.firebase.firestore.collection不是一个函数,TypeError:
NEXT ATTEPMT
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);
  };这种尝试实际上可以从数据库中检索数据(万岁)--但我无法获得想要呈现的文本标签。集合中的每个文档都有两个字段。第一个是标题,第二个是id号,我的最后一步是制作一个标签,它插入了文本(即ABS -),然后将id号和标题放在一起。
我添加了注释代码,以显示提取每个文档标题的效果,但是我试图以我想要的方式使标签变得更好的地方并不会出现错误,它只是不起作用--我仍然只获得列表中的文档标题。
有没有人知道如何使用钩子从云端消防站集合中生成一组选择菜单选项?
发布于 2019-11-14 22:11:13
从“react firebase-hooks/firestore”导入{ useDocument };
为什么?您使用的是useDocumentOnce,当然您需要导入这个函数,而不需要导入不使用的useDocument。
最后一个错误:在初始化const之前就使用了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'; )
https://stackoverflow.com/questions/58813897
复制相似问题