arrays - 使用来自 firebase 集合的键值对填充 react 选择选项数组

标签 arrays reactjs firebase google-cloud-firestore react-select

我正在尝试在我的 React 应用程序中使用一个选项数组,该数组使用 react-select 作为表单以及选项存储在 firebase 集合中的位置。

当我使用键值对定义的选项数组在表单中定义 const 时,这一切都很好,但我正在努力弄清楚如何用存储在 Firebase (Cloud Firestore) 中的集合替换该数组。

在我的形式中,我目前有:

const options = [
  { value: "neurosciences", label: "Neurosciences - ABS 1109" },
  { value: "oncologyCarcinogenesis", label: "Oncology and Carcinogenesis  - ABS 1112" },
  { value: "opticalPhysics", label: "Optical Physics  - ABS 0205" },
  { value: "fisheriesSciences", label: "Fisheries Sciences - ABS 0704" },
  { value: "genetics", label: "Genetics - ABS 0604" },
  { value: "urbanRegionalPlanning", label: "Urban and Regional Planning - ABS 1205" }
];

我想用数据库集合中文档标题的映射替换这个数组。

我的数据库中的文档名称有键,每个文档都有一个名为“标题”的字段。

感谢我的表格选择我有:
<div className="form-group">
                            <label htmlFor="fieldOfResearch">
                            Select your field(s) of research
                            </label>

                            <Select
                            key={`my_unique_select_key__${fieldOfResearch}`}
                            name="fieldOfResearch"
                            isMulti
                            className={
                                "react-select-container" +
                                (errors.fieldOfResearch && touched.fieldOfResearch ? " is-invalid" : "")
                            }
                            classNamePrefix="react-select"
                            value={this.state.selectedValue1}
                            onChange={e => {
                                handleChange1(e);
                                this.handleSelectChange1(e);
                            }}
                            onBlur={setFieldTouched}
                            options={options}
                            />
                            {errors.fieldOfResearch && touched.fieldOfResearch && 
                            <ErrorMessage
                            name="fieldOfResearch"
                            component="div"
                            className="invalid-feedback d-block"
                            />}
                            </div>

我已经阅读了有关使用数组的 firebase 文档,但我遗漏了一些(可能很明显),这使我至少有 20 条不同的路径来执行此操作。

我不确定这是否相关,但我的表单是用 Formik 构建的。

如何使用来自 firebase 数据库集合的键值对映射替换 const 选项数组?

我试图将我的选项常量定义为:
const options = fsDB.collection("abs_for_codes")

但是页面充满了我无法破译的错误。我已阅读本用户指南,但不了解与索引相关的说明,我什至不清楚它们是否是我需要了解的解决此问题的内容。

https://firebase.google.com/docs/firestore/query-data/queries

我也试过:
const options = fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc))
}

但这只是试图理解文档的猜测。

当我尝试 firebase 文档中显示的确切公式时,如下所示:
const options = fsDB.collection("abs_for_codes");

options.get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
        console.log(doc.id, ' => ', doc.data());
    });
});

我得到一整页难以辨认的错误消息,如下所示:
TypeError: options.reduce is not a function
Select.buildMenuOptions
node_modules/react-select/dist/react-select.esm.js:4123
  4120 |   };
  4121 | };
  4122 | 
> 4123 | return options.reduce(function (acc, item, itemIndex) {
       | ^  4124 |   if (item.options) {
  4125 |     // TODO needs a tidier implementation
  4126 |     if (!_this3.hasGroups) _this3.hasGroups = true;
View compiled
new Select
node_modules/react-select/dist/react-select.esm.js:3593
  3590 | 
  3591 | var _selectValue = cleanValue(value);
  3592 | 
> 3593 | var _menuOptions = _this.buildMenuOptions(_props, _selectValue);
       | ^  3594 | 
  3595 | _this.state.menuOptions = _menuOptions;
  3596 | _this.state.selectValue = _selectValue;
View compiled
constructClassInstance
node_modules/react-dom/cjs/react-dom.development.js:11787
  11784 |     new ctor(props, context); // eslint-disable-line no-new
  11785 |   }
  11786 | }
> 11787 | var instance = new ctor(props, context);
        | ^  11788 | var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
  11789 | adoptClassInstance(workInProgress, instance);
  11790 | {
View compiled
updateClassComponent
node_modules/react-dom/cjs/react-dom.development.js:15265
  15262 |   } // In the initial pass we might need to construct the instance.
  15263 | 
  15264 | 
> 15265 |   constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
        | ^  15266 |   mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
  15267 |   shouldUpdate = true;
  15268 | } else if (current$$1 === null) {
View compiled
beginWork
node_modules/react-dom/cjs/react-dom.development.js:16265
  16262 | 
  16263 |     var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
  16264 | 
> 16265 |     return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
        | ^  16266 |   }
  16267 | 
  16268 | case HostRoot:
View compiled
performUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js:20285
  20282 |   startProfilerTimer(workInProgress);
  20283 | }
  20284 | 
> 20285 | next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
        | ^  20286 | workInProgress.memoizedProps = workInProgress.pendingProps;
  20287 | 
  20288 | if (workInProgress.mode & ProfileMode) {
View compiled
workLoop
node_modules/react-dom/cjs/react-dom.development.js:20326
  20323 | if (!isYieldy) {
  20324 |   // Flush work without yielding
  20325 |   while (nextUnitOfWork !== null) {
> 20326 |     nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
        | ^  20327 |   }
  20328 | } else {
  20329 |   // Flush asynchronous work until there's a higher priority event
View compiled
HTMLUnknownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js:147
  144 |     window.event = windowEvent;
  145 |   }
  146 | 
> 147 |   func.apply(context, funcArgs);
      | ^  148 |   didError = false;
  149 | } // Create a global error event handler. We use this to capture the value
  150 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js:196
  193 | // errors, it will trigger our global error handler.
  194 | 
  195 | evt.initEvent(evtType, false, false);
> 196 | fakeNode.dispatchEvent(evt);
      | ^  197 | 
  198 | if (windowEventDescriptor) {
  199 |   Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js:250
  247 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  248 |   hasError = false;
  249 |   caughtError = null;
> 250 |   invokeGuardedCallbackImpl$1.apply(reporter, arguments);
      | ^  251 | }
  252 | /**
  253 |  * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
replayUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js:19509
  19506 | 
  19507 | isReplayingFailedUnitOfWork = true;
  19508 | originalReplayError = thrownValue;
> 19509 | invokeGuardedCallback(null, workLoop, null, isYieldy);
        | ^  19510 | isReplayingFailedUnitOfWork = false;
  19511 | originalReplayError = null;
  19512 | 
View compiled
renderRoot
node_modules/react-dom/cjs/react-dom.development.js:20439
  20436 | if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
  20437 |   if (mayReplay) {
  20438 |     var failedUnitOfWork = nextUnitOfWork;
> 20439 |     replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
        | ^  20440 |   }
  20441 | } // TODO: we already know this isn't true in some cases.
  20442 | // At least this shows a nicer error message until we figure out the cause.
View compiled
performWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js:21363
  21360 |   cancelTimeout(timeoutHandle);
  21361 | }
  21362 | 
> 21363 | renderRoot(root, isYieldy);
        | ^  21364 | finishedWork = root.finishedWork;
  21365 | 
  21366 | if (finishedWork !== null) {
View compiled

另一种尝试:
const options = abs_for_codes.map((title) => {
    <option key={title}
    value={id} />
}

这也不起作用 - 我试过了,因为它看起来类似于 react 数组指令。

附图显示了 firestore 中的数据结构。

data structure

下一次尝试

使用默里的建议,我已经尝试过
import Select from "react-select";
import { fsDB, firebase, settings } from "../../../firebase";

let options = [];

const initialValues = {
  fieldOfResearch: null,

}


class ProjectForm extends React.Component {
  state = {
    selectedValue1: options,
}

handleSelectChange1 = selectedValue1 => {
    this.setState({ selectedValue1 });
  };


componentDidMount() {
    fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        let newOptions = [];
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data());
            newOptions.push({
              value: doc.data().title.replace(/( )/g, ''),
              label: doc.data().title + ' - ABS ' + doc.id
            });
        });
        this.setState({options: newOptions});
    });
}


handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    console.log("SUCCESS!! :-)\n\n", formState);
    fsDB
      .collection("project")
      .add(formState)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        this.setState({ selectedValue1: null });
        this.setState({ selectedValue2: null });
        this.setState({ selectedValue3: null });
        this.setState({ selectedValue4: null });
        this.setState({ selectedValue5: null });
        this.setState({ selectedValue6: null });

        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };


onSubmit={this.handleSubmit}
        render={({ errors, status, touched, setFieldTouched, handleSubmit, values }) => {
          let fieldOfResearch;
          const handleChange1 = optionsObject => {
            fieldOfResearch = optionsObject;
            return (values.fieldOfResearch = optionsObject.value);
          };

<div className="form-group">
                                <label htmlFor="fieldOfResearch">
                                Select your field(s) of research
                                </label>

                                <Select
                                key=
{`my_unique_select_key__${fieldOfResearch}`}
                                name="fieldOfResearch"
                                isMulti
                                className={
                                    "react-select-container" +
                                    (errors.fieldOfResearch && touched.fieldOfResearch ? " is-invalid" : "")
                                }
                                classNamePrefix="react-select"
                                value={this.state.selectedValue1}
                                onChange={e => {
                                    handleChange1(e);
                                    this.handleSelectChange1(e);
                                }}
                                onBlur={setFieldTouched}
                                options={options}
                                />
                                {errors.fieldOfResearch && touched.fieldOfResearch && 
                                <ErrorMessage
                                name="fieldOfResearch"
                                component="div"
                                className="invalid-feedback d-block"
                                />}
                                </div>

因此,逐步完成后,选项作为一个空数组开始,ComponentDidMount 函数将其状态重置为 NewOptions,并将其输入到表单选择下拉列表中。

这一切对我来说都有意义,但它不起作用 - 我只是得到一个空数组。

当我尝试 Avanthika 的建议时,我可以呈现表单并且可以从正确的 db 集合中选择多个选项,但是当我提交表单时没有任何 react 。 React 中的控制台调试器显示出一张不笑的脸(我以前从未见过。下图)。当我删除选择字段时,此表单提交正常。

enter image description here

下次尝试

当我尝试下面每个 Murray R 和 Avinthika 的更新建议时,我可以选择多个字段。但我无法提交表格。如果我删除选择字段,表单将提交。提交formik多字段表单有技巧吗?

我的提交按钮是:
<div className="form-group">
                <Button
                  variant="outline-primary"
                  type="submit"
                  style={style3}
                  id="ProjectId"
                  onClick={handleSubmit}
                  disabled={!dirty || isSubmitting}

                >
                  Save
                </Button>
              </div>

我的句柄提交有:
handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    console.log("SUCCESS!! :-)\n\n", formState);
    fsDB
      .collection("project")
      .add({
          ...(formState),
          createdAt: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(docRef => {
        console.log("docRef>>>", docRef);
        this.setState({ selectedValue1: null, selectedValue2: null, selectedValue3: null, selectedValue4: null, selectedValue5: null, selectedValue6: null });

        // this.setState({ selectedValue1: null });
        // this.setState({ selectedValue2: null });
        // this.setState({ selectedValue3: null });
        // this.setState({ selectedValue4: null });
        // this.setState({ selectedValue5: null });
        // this.setState({ selectedValue6: null });

        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };

控制台不记录任何内容。

下次尝试

我删除并重新安装了 react chrome 扩展程序,然后又可以正常工作了。

附加的屏幕截图显示表单未验证且未提交,但每个表单值的状态都在那里 - 您可以看到截图的底部将表单字段值之一显示为“s”。

enter image description here

进一步尝试

所以 - 我将此表单拆分为一个只有一个字段的表单 - 我一直在尝试处理的选择字段。

该表格在其整体上具有:
import React from 'react';

import { Formik, Form, Field, ErrorMessage, withFormik } from "formik";
import * as Yup from "yup";
import Select from "react-select";
import { fsDB, firebase, settings } from "../../../firebase";

import {
    Badge,
    Button,
    Col,
    ComponentClass,
    Feedback,
    FormControl,
    FormGroup,
    FormLabel,
    InputGroup,
    Table,
    Row,
    Container
  } from "react-bootstrap";

const initialValues = {
    fieldOfResearch: null,
}


class ProjectForm extends React.Component {
    state = {
      options: [],  
      selectedValue1: [],
    }

    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
            });
          }


  handleSelectChange1 = selectedValue1 => {
    this.setState({ selectedValue1 });
  };

  handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    console.log("SUCCESS!! :-)\n\n", formState);
    fsDB
      .collection("project")
      .add({
          ...(formState),
          createdAt: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(docRef => {
        console.log("docRef>>>", docRef);
        this.setState({ selectedValue1: null});


        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };

  render() {
    const { options } = this.state;  
    return (
      <Formik
        initialValues={initialValues}
        validationSchema={Yup.object().shape({
          //   fieldOfResearch: Yup.array().required("What is your field of research?"),
        })}

        onSubmit={this.handleSubmit}
        render={({ errors, status, touched, setFieldTouched, handleSubmit, isSubmitting, dirty, values }) => {
          let fieldOfResearch;
          const handleChange1 = optionsObject => {
            fieldOfResearch = optionsObject;
            return (values.fieldOfResearch = optionsObject.value);
          };
          return (
            <div>
            <Form>
                <div className="form-group">

                                <label htmlFor="fieldOfResearch">
                                Select your field(s) of research
                                </label>
                                <Select
                                    key={`my_unique_select_key__${fieldOfResearch}`}
                                    name="fieldOfResearch"
                                    isMulti
                                    className={
                                        "react-select-container" +
                                        (errors.fieldOfResearch && touched.fieldOfResearch
                                        ? " is-invalid"
                                        : "")
                                    }
                                    classNamePrefix="react-select"
                                    value={this.state.selectedValue1}
                                    onChange={e => {
                                        handleChange1(e);
                                        this.handleSelectChange1(e);
                                    }}
                                    onBlur={setFieldTouched}
                                    options={options}
                                    />    

                                {errors.fieldOfResearch && touched.fieldOfResearch && 
                                <ErrorMessage
                                name="fieldOfResearch"
                                component="div"
                                className="invalid-feedback d-block"
                                />}
                                </div> 
                                <div className="form-group">
                                <Button
                                  variant="outline-primary"
                                  type="submit"
                                  id="ProjectId"
                                  onClick={handleSubmit}
                                //   disabled={!dirty || isSubmitting}

                                >
                                  Save
                                </Button>
                              </div>
                              </Form>

            </div>
        );
    }}
  />
);
}
}

export default ProjectForm;

此表格允许在表格中选择研究领域。 on submit 函数在控制台中工作,在一定程度上它使用 fieldOfResearch 将成功记录为“未定义”。没有任何东西会保留到数据库中。

The error message says: Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field fieldOfResearch) ▶



当我尝试输入字段值并检查 react 值时,错误消息显示:

Uncaught TypeError: Cannot convert undefined or null to object

最佳答案

另一个更新的答案:

The error message says: Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field fieldOfResearch



发生此错误是因为您的表单值无效。您没有保持正确的 formik 状态。

我刚刚尝试过并检查过,表单提交对我来说非常有用。你写了太多多余的代码——我们只需要原生的 formik 方法和 firebase。变更日志如下:
  • react-select 的 onChange 应该使用 Formik 中的 setFieldValue ,如下所示:
  • onChange={selectedOptions => {
       // Setting field value - name of the field and values chosen.
       setFieldValue("fieldOfResearch", selectedOptions)}
    }
    
  • 初始值应该是一个空数组。由于我们已经声明了初始值并且通过 Formik 维护了表单值,因此绝对不需要内部状态管理。即,不需要 this.state.selectedValue1 , handleChange1handleSelectChange1 .如果您查看 Formik HOC 的 render(),您会注意到 values - 这给出了每次更改后表单的当前值。

  • 所以,
    value={this.state.selectedValue1}
    

    应该改为
    value={values.fieldOfResearch}
    
  • 我已经像这样编写了 handleSubmit - 您代码的精确副本。但我只是从所选选项的数组中提取值:
  • handleSubmit = (formState, { resetForm }) => {
      // Now, you're getting form state here!
      const fdb = firebase.firestore();
      const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value)
      }
      console.log("formvalues", payload);
      fdb
      .collection("project")
      .add(payload)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
    }
    

    我可以在控制台中看到表单提交和 docRef。表单也被重置为初始状态。
    import React from "react";
    import { Formik, Form, ErrorMessage } from "formik";
    import * as Yup from "yup";
    import Select from "react-select";
    import firebase from "./firebase";
    import {
      Button,
      Container
    } from "react-bootstrap";
    
    const initialValues = {
      fieldOfResearch: []
    };
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          options: []
        };
      }
    
      async componentWillMount() {
        const fdb = firebase.firestore();
        let options = [];
        await fdb
          .collection("abs_codes")
          .get()
          .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
              options.push({
                value: doc.data().title.replace(/( )/g, ""),
                label: doc.data().title
              });
            });
          });
        this.setState({
          options
        });
      }
    
      handleSubmit = (formState, { resetForm }) => {
        // Now, you're getting form state here!
        const fdb = firebase.firestore();
        const payload = {
          ...formState,
          fieldOfResearch: formState.fieldOfResearch.map(t => t.value)
        }
        console.log("formvalues", payload);
        fdb
        .collection("project")
        .add(payload)
        .then(docRef => {
          console.log("docRef>>>", docRef);
          resetForm(initialValues);
        })
        .catch(error => {
          console.error("Error adding document: ", error);
        });
      }
    
      render() {
        const { options } = this.state;
        return (
          <Container>
            <Formik
              initialValues={initialValues}
              validationSchema={Yup.object().shape({
                  fieldOfResearch: Yup.array().required("What is your field of research?"),
              })}
              onSubmit={this.handleSubmit}
              render={({
                errors,
                status,
                touched,
                setFieldValue,
                setFieldTouched,
                handleSubmit,
                isSubmitting,
                dirty,
                values
              }) => {
                return (
                  <div>
                    <Form>
                      <div className="form-group">
                        <label htmlFor="fieldOfResearch">
                          Select your field(s) of research
                        </label>
                        <Select
                          key={`my_unique_select_keyfieldOfResearch`}
                          name="fieldOfResearch"
                          isMulti
                          className={
                            "react-select-container" +
                            (errors.fieldOfResearch && touched.fieldOfResearch
                              ? " is-invalid"
                              : "")
                          }
                          classNamePrefix="react-select"
                          value={values.fieldOfResearch}
                          onChange={selectedOptions => {
                            setFieldValue("fieldOfResearch", selectedOptions)}
                          }
                          onBlur={setFieldTouched}
                          options={options}
                        />
                        {errors.fieldOfResearch && touched.fieldOfResearch &&
                          <ErrorMessage
                             name="fieldOfResearch"
                             component="div"
                             className="invalid-feedback d-block"
                          />
                        }
                      </div>
                      <div className="form-group">
                        <Button
                          variant="outline-primary"
                          type="submit"
                          id="ProjectId"
                          onClick={handleSubmit}
                          disabled={!dirty || isSubmitting}
                        >
                          Save
                        </Button>
                      </div>
                    </Form>
                  </div>
                );
              }}
            />
          </Container>
        );
      }
    }
    
    export default App;
    

    只需尝试先复制粘贴,然后再尝试进行更改。我想这应该对你有帮助!

    更新答案:

    嗨梅尔,我只是在我的系统中设置了整个事情并尝试为你做,虽然我不能与你分享信用,我想这应该会有所帮助。
  • Javascript 不是同步的。您的 componentDidMount 不会等待您尝试从 firebase 获取的数据。它只会在您的查询返回响应之前设置状态。
  • 他们的关键是等待回应。我已经以这种方式编辑了代码,并且可以在我的控制台上的 render() 中看到选项。
  • import React from 'react';
    import firebase from "./firebase.js";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.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
            });
          });
        });
        this.setState({
          options
        });
      }
    
      render() {
        console.log(this.state);
        const { options } = this.state;
        return (
          <div className="form-group">
            <label htmlFor="fieldOfResearch">
              Select your field(s) of research
            </label>
    
            <Select
              key={`my_unique_select_key__${fieldOfResearch}`}
              name="fieldOfResearch"
              isMulti
              className={
                "react-select-container" +
                (errors.fieldOfResearch && touched.fieldOfResearch
                  ? " is-invalid"
                  : "")
              }
              classNamePrefix="react-select"
              value={this.state.selectedValue1}
              onChange={e => {
                handleChange1(e);
                this.handleSelectChange1(e);
              }}
              onBlur={setFieldTouched}
              options={options}
            />
          </div>
        );
      }
    }
    
    export default App;
    

    让我知道这是否适合您!

    我不禁注意到,为什么 handleSubmit 中有这么多 setState?你强制你的组件重新渲染很多次。相反,您可以这样做:
    handleSubmit = (formState, { resetForm }) => {
        // Now, you're getting form state here!
        console.log("SUCCESS!! :-)\n\n", formState);
        fsDB
          .collection("project")
          .add(formState)
          .then(docRef => {
            console.log("docRef>>>", docRef);
            this.setState({ selectedValue1: null, selectedValue2: null, selectedValue3: null, selectedValue4: null, selectedValue5: null, selectedValue6: null });
            resetForm(initialValues);
          })
          .catch(error => {
            console.error("Error adding document: ", error);
          });
      };
    
    

    关于arrays - 使用来自 firebase 集合的键值对填充 react 选择选项数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987388/

    相关文章:

    c++ - jsoncpp 只写一个元素的json数组

    c - 使用指针而不是索引进行排序

    python - 如何检查两个列表的元素组合是否存在于第三个列表中?

    android - 如何使用服务器时间在 Firestore 中设置纪元

    javascript - 如何解决 Firebase 函数中的嵌套异步数据库调用

    java - Firebase signInWithEmailAndPassword 总是跳到其他

    javascript - 使用 CoffeeScript 从对象数组中选择一个字段

    javascript - 如何在 React JS 中使用 LESS 变量

    javascript - react 克隆/创建元素

    javascript - react HOC : render hijacking with functional components