【发布时间】: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