简体   繁体   English

UsefieldArray 反应钩子形式仅删除最后一个元素

[英]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.

相关问题 React Native 中的 React-Hook-Form useFieldArray - React-Hook-Form useFieldArray in React Native react-hook-form id 未使用 useFieldArray 保存 - react-hook-form id not saved with useFieldArray 维护 useFieldArray react-hook-form 的状态 - Maintain state of useFieldArray react-hook-form React Hook Form 在 useFieldArray 列表之间移动项目 - React Hook Form move items between useFieldArray lists 如何使用 useFieldArray 钩子验证 React Hook Form 中的数组字段? - How can I validate array field in React Hook Form with the useFieldArray hook? 为什么在 react-hook-form 中对动态表单使用 useFieldArray() 时不能关注当前字段? - Why can't I focus on the current field when using useFieldArray() for dynamic form in react-hook-form? 如何使用带有 useFieldArray 的 react-hook-form 在动态表单上使用 yup 验证 - How to use yup validation on dynamic form using react-hook-form with useFieldArray React-hook-form 必须按两次才能删除输入的最后一个字符,两次才能输入第一个字符 - React-hook-form Have to press twice for deleting the last character of input and twice for enter the first character 拼接删除反应中对象数组的最后一个元素 - Splice deleting last element of an array of object in react React - 从列表中间删除会删除最后一个元素 - React - Deleting from middle of list removes last element instead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM