JSReact,删除除最后一项以外的任何动态添加的表单内容会擦除表单

JSReact, Deleting any dynamically added form content other than last item wipes the form

我正在构建一个带有动态添加字段的表单,并且正在研究在用户改变主意时删除字段的功能。当删除最后添加的项目时,它按预期工作,但如果我有,例如,3 个动态添加的字段并删除第二个,它会暂时工作,然后将整个表单擦除干净。有谁知道为什么会这样?

Codesandbox link here,但我包括(我认为是)以下所有相关代码:

来自“form.js”:

import React, { useState } from "react";
import CreditInputs from "./CreditInputs";

...


// Create an array that is all current credits except the one being deleted, set credit state to reflect new list
    const handleDeleteCredit = (e) => {
    const updatedCredits = [...creditState];
    updatedCredits.splice(parseInt(e.target.dataset.idx), 1)
    setCreditState(updatedCredits);
}

return (
    <form>            
        <label htmlFor="title">Title</label>   
        <input type="text" name="title" id="title" value={productionState.title} onChange={handleProductionChange} /> 
        <label htmlFor="production_note">Production Note</label> 
        <input type="textarea" name="production_note" id="production_note" value={productionState.production_note} onChange={handleProductionChange} />
        {
            creditState.map((val, idx) => (
                    <CreditInputs
                        key={`credit-${idx}`}
                        idx={idx}
                        creditState={creditState}
                        handleCreditChange={handleCreditChange}
                        // Pass each credit the handleDeleteCredit function
                        handleDeleteCredit={handleDeleteCredit}
                    />
            ))   
        }
        <input type="button" value="Add New Credit" onClick={addCredit}/>       
        <input type="submit" value="Submit" />        
    </form>
)
}

export default Form;

来自“CreditInputs.js”:

import React from "react";
import PropTypes from "prop-types";

// Take in the handleDeleteCredit function
    const CreditInputs = ({
        idx,
        creditState,
        handleCreditChange,
        handleDeleteCredit
     }) => {
    const creditId = `name-${idx}`;
    const roleId = `role-${idx}`;
    const bioId = `bio-${idx}`;

    return (
       <div key={`credit-${idx}`}>
       <label htmlFor={creditId}>{`Credit #${idx + 1} Name`}</label>
       
       ...

       {/* Make Delete Button */}
       <button data-idx={idx} onClick={handleDeleteCredit}>Delete Credit</button>
       </div>
     );
     };

     CreditInputs.propTypes = {
       idx: PropTypes.number,
       creditState: PropTypes.array,
       handleCreditChange: PropTypes.func,
       //   Assign handleDeleteCredit a PropType
       handleDeleteCredit: PropTypes.func
     };

     export default CreditInputs;

如有任何想法,我们将不胜感激!

您必须在 handleDeleteCredit 的顶部调用 e.preventDefault()。问题是默认表单行为,结果是整个页面重新加载。

 const handleDeleteCredit = (e) => {
    e.preventDefault();
    const updatedCredits = [...creditState];
    updatedCredits.splice(parseInt(e.target.dataset.idx), 1)
    setCreditState(updatedCredits);
}