react hook form的useFieldArray不显示数据

huangapple go评论87阅读模式
英文:

useFieldArray of react hook form not showing data

问题

你好,我已经为你翻译了你提供的代码部分:

<Box component="form" onSubmit={handleSubmit(submit)}>
  <Grid container spacing={2}>
    <Grid item xs={12} sm={12} md={12} lg={12}>
      <TextField
        label="活动名称"
        fullWidth
        {...register("eventName")}
        name="eventName"
      />
    </Grid>

    <Grid item xs={12} sm={12} md={6} lg={6} alignSelf="center">
      <TextField
        label="活动场馆名称"
        fullWidth
        {...register("eventVenue")}
        name="eventVenue"
      />
    </Grid>
    <Box sx={{ width: "100%" }}>
      <DialogTitle
        sx={{ fontWeight: "bold", textTransform: "uppercase" }}
      >
        票务类别
      </DialogTitle>
    </Box>
    <Grid item xs={12} sm={12} md={5} lg={4}>
      <TextField
        label="类别"
        fullWidth
        {...register("ticketCatName")}
        name="ticketCatName"
      />
    </Grid>

    <Grid item xs={12} sm={12} md={3} lg={3}>
      <TextField
        type="number"
        label="价格"
        fullWidth
        {...register("ticketCatPrice")}
        name="ticketCatPrice"
      />
    </Grid>

    <Grid item xs={12} sm={12} md={3} lg={3}>
      <TextField
        type="number"
        label="总数"
        fullWidth
        {...register("ticketCatTotal")}
        name="ticketCatTotal"
      />
    </Grid>
  </Grid>
  这些值是在我提交表单时获取的
</Box>
{fields.map((item, index) => {
  return (
    <MoreFields
      register={register}
      key={item.id}
      remove={remove}
      index={index}
      item={item}
      control={control}
    />
  );
})}
import { Box, Grid, IconButton, SvgIcon, TextField } from "@mui/material";
import React from "react";
import DeleteIcon from '@mui/icons-material/Delete';
import { Fragment } from "react";

const MoreFields = ({ register, remove, index, item }) => {
  return (
    <Fragment key={item.id}>
      <Grid item xs={12} sm={12} md={5} lg={4}>
        <TextField
          label="类别"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatName`)}
          name={`ticketCategory${index}.ticketCatName`}
          defaultValue={item.ticketCatName}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="价格"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatPrice`)}
          name={`ticketCategory${index}.ticketCatPrice`}
          defaultValue={item.ticketCatPrice}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="总数"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatTotal`)}
          name={`ticketCategory${index}.ticketCatTotal`}
          defaultValue={item.ticketCatTotal}
        />
      </Grid>

      <Grid item xs={4} sm={4} md={2} lg={2} alignSelf="center">
        <SvgIcon color='error' onClick={() => remove(index)} sx={{ cursor: 'pointer' }}>
          <DeleteIcon size="medium" />
        </SvgIcon>
      </Grid>
    </Fragment>
  );
};

export default MoreFields;
const { register, handleSubmit, control } = useForm();
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
  {
    control,
    name: "ticketCategory",
  }
);
const addFields = () => {
  append({ ticketCatName: "", ticketCatPrice: "", ticketCatTotal: "" });
};

const submit = (data) => {
  console.log(data);
};

希望这可以帮助你解决问题。如果还有其他问题,请随时提出。

英文:

Hello guys I have created a material UI form with the help of react hook form and useFieldArray hook.

 &lt;Box component=&quot;form&quot; onSubmit={handleSubmit(submit)}&gt;
&lt;Grid container spacing={2}&gt;
&lt;Grid item xs={12} sm={12} md={12} lg={12}&gt;
&lt;TextField
label=&quot;Evnet Name&quot;
fullWidth
{...register(&quot;eventName&quot;)}
name=&quot;eventName&quot;
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={12} md={6} lg={6} alignSelf=&quot;center&quot;&gt;
&lt;TextField
label=&quot;Evnet Venue Name&quot;
fullWidth
{...register(&quot;eventVenue&quot;)}
name=&quot;eventVenue&quot;
/&gt;
&lt;/Grid&gt;
&lt;Box sx={{ width: &quot;100%&quot; }}&gt;
&lt;DialogTitle
sx={{ fontWeight: &quot;bold&quot;, textTransform: &quot;uppercase&quot; }}
&gt;
Ticket Category
&lt;/DialogTitle&gt;
&lt;/Box&gt;
&lt;Grid item xs={12} sm={12} md={5} lg={4}&gt;
&lt;TextField
label=&quot;Category&quot;
fullWidth
{...register(&quot;ticketCatName&quot;)}
name=&quot;ticketCatName&quot;
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={12} md={3} lg={3}&gt;
&lt;TextField
type=&quot;number&quot;
label=&quot;Price&quot;
fullWidth
{...register(&quot;ticketCatPrice&quot;)}
name=&quot;ticketCatPrice&quot;
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={12} md={3} lg={3}&gt;
&lt;TextField
type=&quot;number&quot;
label=&quot;Total&quot;
fullWidth
{...register(&quot;ticketCatTotal&quot;)}
name=&quot;ticketCatTotal&quot;
/&gt;
&lt;/Grid&gt;
This Values I am getting when I submit the form. 
&lt;/Box&gt;

I have create a dynamic form component which I am showing with map.

{fields.map((item, index) =&gt; {
return (
&lt;MoreFields
register={register}
key={item.id}
remove={remove}
index={index}
item={item}
control={control}
/&gt;
);
})}

The value on fields array is not showing data when I submit the form, other fields which not in fields array is working fine.

This is the code of <MoreFields/> component.

import { Box, Grid, IconButton, SvgIcon, TextField } from &quot;@mui/material&quot;;
import React from &quot;react&quot;;
import DeleteIcon from &#39;@mui/icons-material/Delete&#39;;
import { Fragment } from &quot;react&quot;;
const MoreFields = ({ register, remove, index, item }) =&gt; {
return (
&lt;Fragment key={item.id}&gt;
&lt;Grid item xs={12} sm={12} md={5} lg={4}&gt;
&lt;TextField
label=&quot;Category&quot;
fullWidth
{...register(`ticketCategory.${index}.ticketCatName`)}
name={`ticketCategory${index}.ticketCatName`}
defaultValue={item.ticketCatName}
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={12} md={3} lg={3}&gt;
&lt;TextField
type=&quot;number&quot;
label=&quot;Price&quot;
fullWidth
{...register(`ticketCategory.${index}.ticketCatPrice`)}
name={`ticketCategory${index}.ticketCatPrice`}
defaultValue={item.ticketCatPrice}
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={12} md={3} lg={3}&gt;
&lt;TextField
type=&quot;number&quot;
label=&quot;Total&quot;
fullWidth
{...register(`ticketCategory.${index}.ticketCatTotal`)}
name={`ticketCategory${index}.ticketCatTotal`}
defaultValue={item.ticketCatTotal}
/&gt;
&lt;/Grid&gt;
&lt;Grid item xs={4} sm={4} md={2} lg={2} alignSelf=&quot;center&quot;&gt;
&lt;SvgIcon color=&#39;error&#39; onClick={()=&gt;remove(index)} sx={{cursor:&#39;pointer&#39;}}&gt;
&lt;DeleteIcon size=&quot;medium&quot; /&gt;
&lt;/SvgIcon&gt;
&lt;/Grid&gt;
&lt;/Fragment&gt;
);
};
export default MoreFields;

I can get form when I append and even can delete the fields also but when submit value is not coming. don't know why please help me.

hooks and function I am using for this.

const { register, handleSubmit, control } = useForm();
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control,
name: &quot;ticketCategory&quot;,
}
);
const addFields = () =&gt; {
append({ ticketCatName: &quot;&quot;, ticketCatPrice: &quot;&quot;, ticketCatTotal: &quot;&quot; });
};
const submit = (data) =&gt; {
console.log(data);
};

答案1

得分: 1

你应该在注册和名称属性中使用相同的名称,就像这样:

<TextField
  label="Category"
  fullWidth
  {...register(`ticketCategory.${index}.ticketCatName`)}
  name={`ticketCategory.${index}.ticketCatName`}
  defaultValue={item.ticketCatName}
/>;

React Hook Form要求你在数组名称中添加索引,因为它使用点表示法来访问嵌套字段。例如,假设你有一个对象数组如下所示:

{
  "ticketCategory": [
    {
      "ticketCatName": "A",
      "ticketCatPrice": 10,
      "ticketCatTotal": 100
    },
    {
      "ticketCatName": "B",
      "ticketCatPrice": 20,
      "ticketCatTotal": 200
    }
  ]
}

然后,每个输入名称应该与表单数据中字段的路径匹配。例如,第一个票类别名称输入应该具有名称 ticketCategory.0.ticketCatName,第二个票类别价格输入应该具有名称 ticketCategory.1.ticketCatPrice。这样,React Hook Form可以控制表单数据的输入值。

英文:

You should use the same name for both register and name prop like this:

&lt;TextField
label=&quot;Category&quot;
fullWidth
{...register(`ticketCategory.${index}.ticketCatName`)}
name={`ticketCategory.${index}.ticketCatName`}
defaultValue={item.ticketCatName}
/&gt;;

React Hook Form needs you to put the index in the array name because it uses the dot notation to access nested fields. For example, suppose you have an array of objects like this:

{
&quot;ticketCategory&quot;: [
{
&quot;ticketCatName&quot;: &quot;A&quot;,
&quot;ticketCatPrice&quot;: 10,
&quot;ticketCatTotal&quot;: 100
},
{
&quot;ticketCatName&quot;: &quot;B&quot;,
&quot;ticketCatPrice&quot;: 20,
&quot;ticketCatTotal&quot;: 200
}
]
}

Then each input name should match the path of the field in the form data. For example, the first ticket category name input should have the name ticketCategory.0.ticketCatName, and the second ticket category price input should have the name ticketCategory.1.ticketCatPrice. This way, React Hook Form can control the input value to the form data.

huangapple
  • 本文由 发表于 2023年7月14日 00:37:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定