Javascript React hooks form,从简化的数组中设置默认值并不';不填充,但手动输入相同的对象
我使用的是react hooks表单,我试图设置表单的默认值,该表单通过映射数组并输出表单中的输入来输出。我已经将数组简化为这样一个对象Javascript React hooks form,从简化的数组中设置默认值并不';不填充,但手动输入相同的对象,javascript,reactjs,state,reduce,react-forms,Javascript,Reactjs,State,Reduce,React Forms,我使用的是react hooks表单,我试图设置表单的默认值,该表单通过映射数组并输出表单中的输入来输出。我已经将数组简化为这样一个对象{name0:“fijs”,name1:“3838”…},如果我手动将其传递到默认值中,它将映射到我的输入并填充它们。但是,如果我从执行reduce函数的变量中输入它们,它不会填充它。我认为这是因为在第一次渲染时它是未定义的。我试过使用useEffect,但是没有用,所以我被卡住了 这是我正在编写的代码的一部分 const test = formState?.r
{name0:“fijs”,name1:“3838”…}
,如果我手动将其传递到默认值中,它将映射到我的输入并填充它们。但是,如果我从执行reduce函数的变量中输入它们,它不会填充它。我认为这是因为在第一次渲染时它是未定义的。我试过使用useEffect,但是没有用,所以我被卡住了
这是我正在编写的代码的一部分
const test = formState?.reduce((obj, item, idx) => {
return { ...obj, [`${item.name}${idx}`]: "fdsjfs" };
}, {});
const { register, handleSubmit, errors } = useForm({
defaultValues: test,
});
console.log(test);
这就是全部
import { useQuery, gql, useMutation } from "@apollo/client";
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { useForm } from "react-hook-form";
const INPUT_VALUES = gql`
query GetInputValues {
allFormInputVals {
data {
name
_id
type
}
}
}
`;
const ADD_INPUT_VALUES = gql`
mutation AddInputValues(
$name: String!
$type: String!
$index: Int!
$ID: ID!
) {
createFormInputVal(
data: {
name: $name
type: $type
index: $index
formRoot: { connect: $ID }
}
) {
name
}
}
`;
const Home = () => {
const blankFormInput = {
__typename: "FormInputVal",
name: "test",
_id: uuidv4(),
type: "text",
};
const [formState, setFormState] = useState([blankFormInput]);
const [formStateVals, setFormStateVals] = useState(undefined);
const { loading, error, data } = useQuery(INPUT_VALUES);
const [createFormInputVal, { data: createInputData }] = useMutation(
ADD_INPUT_VALUES
);
useEffect(() => {
setFormState(data?.allFormInputVals?.data);
}, [data]);
const test = formState?.reduce((obj, item, idx) => {
return { ...obj, [`${item.name}${idx}`]: "fdsjfs" };
}, {});
const { register, handleSubmit, errors } = useForm({
defaultValues: test,
});
console.log(test);
const onSubmit = (data) => console.log(data);
console.log(errors);
const addInput = async () => {
const blanktext = {
__typename: "FormInputVal",
name: "Product Image",
_id: uuidv4(),
type: "text",
};
setFormState([...formState, { ...blanktext }]);
console.log(formState);
const res = await createFormInputVal({
variables: {
name: "test",
type: "text",
index: 0,
ID: "291541554941657608",
},
}).catch(console.error);
console.log(res);
};
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="button" value="Add Form Input" onClick={addInput} />
{formState?.map((val, idx) => {
const nameId = `name${idx}`;
const typeId = `type-${idx}`;
return (
<div key={val._id}>
{val.type === "text" && (
<>
<label htmlFor={nameId}>{`${val.name} #${idx + 1}`}</label>
<input
type="text"
name={nameId}
id={nameId}
className={val.type}
ref={register()}
/>
{/* <label htmlFor={typeId}>{`Type #${idx + 1}`}</label>
<select name={typeId} id={typeId} className={val.type}>
{data.allFormInputVals.data.map((item) => {
return (
<option key={item._id} value={item.type}>
{item.type}
</option>
);
})}
</select> */}
</>
)}
</div>
);
})}
<button type="submit">Save Form</button>
</form>
</>
);
};
export default Home;
更新:我将表单抽象到它;它有自己的组件,但仍然不起作用
Form.js
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useQuery, gql, useMutation } from "@apollo/client";
import { v4 as uuidv4 } from "uuid";
const ADD_INPUT_VALUES = gql`
mutation AddInputValues(
$name: String!
$type: String!
$index: Int!
$ID: ID!
) {
createFormInputVal(
data: {
name: $name
type: $type
index: $index
formRoot: { connect: $ID }
}
) {
name
}
}
`;
export default function Form({ formState, setFormState }) {
const test = formState?.reduce((obj, item, idx) => {
return { ...obj, [`${item.name}${idx}`]: "fdsjfs" };
}, {});
console.log(test);
const { register, handleSubmit, errors } = useForm({ defaultValues: test });
const [formStateVals, setFormStateVals] = useState(undefined);
// console.log(test);
const onSubmit = (data) => console.log(data);
console.log(errors);
const addInput = async () => {
const blanktext = {
__typename: "FormInputVal",
name: "Product Image",
_id: uuidv4(),
type: "text",
};
setFormState([...formState, { ...blanktext }]);
console.log(formState);
const res = await createFormInputVal({
variables: {
name: "test",
type: "text",
index: 0,
ID: "291541554941657608",
},
}).catch(console.error);
console.log(res);
};
const [createFormInputVal, { data: createInputData }] = useMutation(
ADD_INPUT_VALUES
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="button" value="Add Form Input" onClick={addInput} />
{formState?.map((val, idx) => {
const nameId = `name${idx}`;
const typeId = `type-${idx}`;
return (
<div key={val._id}>
{val.type === "text" && (
<>
<label htmlFor={nameId}>{`${val.name} #${idx + 1}`}</label>
<input
type="text"
name={nameId}
id={nameId}
className={val.type}
ref={register()}
/>
{/* <label htmlFor={typeId}>{`Type #${idx + 1}`}</label>
<select name={typeId} id={typeId} className={val.type}>
{data.allFormInputVals.data.map((item) => {
return (
<option key={item._id} value={item.type}>
{item.type}
</option>
);
})}
</select> */}
</>
)}
</div>
);
})}
<button type="submit">Save Form</button>
</form>
);
}
从“react”导入{useffect,useState};
从“react hook form”导入{useForm};
从“@apollo/client”导入{useQuery,gql,useVaritation};
从“uuid”导入{v4 as uuidv4};
const ADD_INPUT_VALUES=gql`
突变附加值(
$name:String!
$type:String!
$index:Int!
$ID:ID!
) {
createFormInputVal(
数据:{
姓名:$name
类型:$type
索引:$index
formRoot:{connect:$ID}
}
) {
名称
}
}
`;
导出默认函数形式({formState,setFormState}){
常量测试=formState?.reduce((对象,项目,idx)=>{
返回{…obj,[`${item.name}${idx}`]:“fdsjfs”};
}, {});
控制台日志(测试);
const{register,handleSubmit,errors}=useForm({defaultValues:test});
常量[formStateVals,setFormStateVals]=useState(未定义);
//控制台日志(测试);
const onSubmit=(数据)=>console.log(数据);
console.log(错误);
常量addInput=async()=>{
常量空白文本={
__typename:“FormInputVal”,
名称:“产品形象”,
_id:uuidv4(),
键入:“文本”,
};
setFormState([…formState,{…blanktext}]);
console.log(formState);
const res=等待createFormInputVal({
变量:{
名称:“测试”,
键入:“文本”,
索引:0,
ID:“291541554941657608”,
},
}).catch(控制台错误);
控制台日志(res);
};
const[createFormInputVal,{data:createInputData}]=useCommutation(
添加输入值
);
返回(
{formState?.map((val,idx)=>{
const nameId=`name${idx}`;
const typeId=`type-${idx}`;
返回(
{val.type===“文本”&&(
{`${val.name}{idx+1}`}
{/*{Type}${idx+1}}
{data.allFormInputVals.data.map((项)=>{
返回(
{item.type}
);
})}
*/}
)}
);
})}
保存形式
);
}
index.js
import { useQuery, gql, useMutation } from "@apollo/client";
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import Form from "../components/Form";
const INPUT_VALUES = gql`
query GetInputValues {
allFormInputVals {
data {
name
_id
type
}
}
}
`;
const Home = () => {
const blankFormInput = {
__typename: "FormInputVal",
name: "test",
_id: uuidv4(),
type: "text",
};
const [formState, setFormState] = useState([blankFormInput]);
const { loading, error, data } = useQuery(INPUT_VALUES);
useEffect(() => {
const formData = data?.allFormInputVals?.data;
setFormState(formData);
}, [data]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<>
<Form formState={formState} setFormState={setFormState} />
</>
);
};
export default Home;
从“@apollo/client”导入{useQuery,gql,useMutation};
从“react”导入{useffect,useState};
从“uuid”导入{v4 as uuidv4};
从“./组件/表格”导入表格;
常量输入值=gql`
查询GetInputValues{
所有形式的输入{
资料{
名称
_身份证
类型
}
}
}
`;
常量Home=()=>{
常量blankFormInput={
__typename:“FormInputVal”,
名称:“测试”,
_id:uuidv4(),
键入:“文本”,
};
常量[formState,setFormState]=使用状态([blankFormInput]);
const{loading,error,data}=useQuery(输入值);
useffect(()=>{
const formData=数据?.allFormInputVals?.data;
setFormState(formData);
},[数据];
如果(加载)返回加载…;
if(error)返回错误:{error.message};
返回(
);
};
导出默认主页;
您可以将表单提取到它自己的组件中,并仅在获取数据时呈现它。这样,当您在子组件中使用useForm
时,将正确设置默认值
const Home = () => {
const { loading, error, data } = useQuery(INPUT_VALUES)
const blankFormInput = {
__typename: "FormInputVal",
name: "test",
_id: uuidv4(),
type: "text",
}
const [formState, setFormState] = useState([blankFormInput])
// other code
if (loading) {
return <p>Loading...</p>
}
return <MyForm defaultValues={formState} />
}
formState
来自哪里?formState由graphql数据库查询填充。useffect(()=>{setFormState(data?.allFormInputVals?.data);},[data])代码>我尝试了抽象组件解决方案,但仍然没有填充值。我已经在上面发布了我的更新代码。哦,我刚刚在表单componenet周围添加了一个复选框,它成功了。谢谢``{formState&&}```@AndersKitson不确定我是否理解添加条件是如何解决问题的<默认情况下,code>formState
是一个数组(真实值)。我也不是,嗯。。。
const Home = () => {
const { loading, error, data } = useQuery(INPUT_VALUES)
const blankFormInput = {
__typename: "FormInputVal",
name: "test",
_id: uuidv4(),
type: "text",
}
const [formState, setFormState] = useState([blankFormInput])
// other code
if (loading) {
return <p>Loading...</p>
}
return <MyForm defaultValues={formState} />
}
useEffect(() => {
const formData = data?.allFormInputVals?.data
setFormState(formData)
formData?.forEach((item, idx) => {
setValue(`${item.name}${idx}`, 'whatever')
})
}, [data])