gpt4 book ai didi

reactjs - React Hook 形式 - 填充选择多个选项数组

转载 作者:行者123 更新时间:2023-12-05 07:17:39 24 4
gpt4 key购买 nike

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

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

formik 中,我已经成功地使用了这个 componentDidMount 异步方法从数据库中获取记录并将它们提供给 select 方法。我无法让它与 react 钩子(Hook)一起工作。

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}

我无法让它以 react Hook 形式工作,我正在尝试学习如何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 的东西。

最佳答案

使用 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();
}, []);

然后你可以使用options={options}在你的<select> .请记住,使用钩子(Hook)你的选项应该使用 useState钩子(Hook):

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

关于reactjs - React Hook 形式 - 填充选择多个选项数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58707937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com