【问题标题】:React hook form - populate select many options array反应钩子形式 - 填充选择许多选项数组
【发布时间】:2019-11-05 09:12:13
【问题描述】:

我正在尝试使用react-hook-form 制作一个选择菜单,从中可以选择多个选项。

我有一个数据库数组,其中包含我想用来填充选择菜单的记录。

formik中,我已经成功使用了componentDidMount这个异步方法从数据库中获取记录,交给select方法。我无法让它与 react hooks 一起使用。

state = {
      options: [],
    }

    async componentDidMount() {
        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
        });
    }

然后我可以在选择菜单中使用 const 来获取下拉菜单项,如下所示:

options={options}

我无法让它以反应钩子形式工作,我正在尝试学习如何 useEffect,我认为它应该取代这种方法。

但是,我不知道如何开始。

我当前的表单是一个片段(以便我可以在前端的其余部分继续使用 antd),它具有:

import React from "react";
import useForm from "react-hook-form";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { StateMachineProvider, createStore } from "little-state-machine";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import { fsDB, firebase, settings } from "../../../firebase";

import updateAction from "./updateAction";
import "./styles.css";


createStore({
  data: {}
});


const General = props => {
  const { register, handleSubmit, errors } = useForm();
  const { action } = useStateMachine(updateAction);
  const onSubit = data => {
    action(data);
    props.history.push("./ProposalMethod");
  };

  return (

      <React.Fragment>
        <form onSubmit={handleSubmit(onSubit)}>
          <h2>Part 1: General</h2>
          <label>
            Title
            <input 
              type="text" 
              name="title"  
              placeholder="The title " 
              ref={register({ required: true })} 
            />
          </label>
          {errors.title && <p id="titleError">A title is required</p>}

          <label>
            Subtitle
            <input 
              type="text" 
              name="subtitle"  
              placeholder="An optional subtitle" 
              ref={register} 
            />
          </label>

          <label>Select your fields </label>
          <Select 
            name="field" 
            placeholder="Select" 
            options={options}
          />
          <input type="submit" value="next" />

        </form>
      </React.Fragment>  
  );
}; 

export default withRouter(General);

谁能看出我哪里出错了?

我不知道如何将 componentDidMount 替换为适用于 react-hook-form 的东西。

【问题讨论】:

  • 您是否有机会为您的问题提供代码框?
  • 嗨布鲁斯 - 这是一个沙箱 - 我已经注释掉了对数据库的调用 - 我无法共享对数据库的访问权限,但我有一组我想要的值和标签填充选择:codesandbox.io/s/react-hook-form-wizard-form-sl3po

标签: reactjs react-hooks side-effects react-hook-form


【解决方案1】:

使用useEffect 执行与使用componentDidMount 时相同的行为,您应该在useEffect 方法中调用相同的操作,但在其中创建一个函数,然后调用它:

useEffect(() => {
    populateOptions() => {
        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
                });
            });
        });
    }
    populateOptions();
}, []);

然后你可以在你的&lt;select&gt; 中使用options={options}。 请记住,使用钩子你的选项应该是使用useState钩子:

const [options, setOptions] = useState([]);

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 2022-01-02
    • 2016-09-13
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多