[英]UsefieldArray react hook form deleting the last element only
I'm having a trouble with react hook form usefield array.我在使用反应钩子表单 usefield 数组时遇到问题。 Basically I'm trying to append and delete but the problem is when I'm deleting its deleting only the last element.基本上我正在尝试 append 并删除,但问题是当我删除它时只删除最后一个元素。 append is working fine but suppose if I have 3 fields with values a,b,c and I want to remove b, when I'm pressing remove button of b then its removing c, if I try to remove a again its also removing c only from the UI. append is working fine but suppose if I have 3 fields with values a,b,c and I want to remove b, when I'm pressing remove button of b then its removing c, if I try to remove a again its also removing c仅来自用户界面。
Here is my codesandbox link for the code: Codesandbox这是我的codesandbox代码链接: Codesandbox
I made some changes to your codesandbox and this should work:我对您的代码框进行了一些更改,这应该可以工作:
import React from "react";
import { useForm, useFieldArray, Controller, useWatch } from "react-hook-form";
import ReactDOM from "react-dom";
// import Button from '@mui/material/Button';
import "./styles.css";
let renderCount = 0;
function App() {
const { register, control, handleSubmit, reset, watch } = useForm({
defaultValues: {
parameters: [{ parameterName: "" }]
}
});
const {
fields: parameterfields,
append: appendParameters,
remove: removeParameters
} = useFieldArray({
control,
name: "parameters"
});
const onSubmit = (data) => console.log("data", data);
// if you want to control your fields with watch
// const watchResult = watch("test");
// console.log(watchResult);
// The following is useWatch example
// console.log(useWatch({ name: "test", control }));
renderCount++;
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h1>Field Array </h1>
<p>The following demo allow you to delete, append, prepend items</p>
<span className="counter">Render Count: {renderCount}</span>
<ul>
{parameterfields.map((item, index) => {
return (
<div
key={item.id}
style={{ display: "flex", marginTop: 30 }}
>
<div style={{ width: "90%", marginRight: 20 }}>
<Controller
name={`parameters.${index}.parameterName`}
control={control}
render={({ field: { onChange, value } }) => (
<div>
{console.log(item.parameterName)}
<input
name={`parameters[${index}].parameterName`}
variant="standard"
InputProps={{
disableUnderline: true
}}
// className={styles.title}
onChange={onChange}
defaultValue={item.parameterName}
placeholder="Parameter Name"
/>
</div>
)}
/>
</div>
<div>
<button
onClick={() => removeParameters(index)}
sx={{ width: 130, height: 50 }}
variant="outlined"
>
Remove
</button>
</div>
</div>
);
})}
</ul>
<section>
<button
type="button"
onClick={() => {
appendParameters({
date: new Date(),
parameterName: "" });
}}
>
append
</button>
</section>
<input type="submit" />
</form>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.