You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中提交表单时向数组添加对象失败求助

问题分析与解决方案

你的表单添加功能失效的核心问题在Form组件的submitForm函数参数处理错误,另外还有一处可以优化的地方,具体修正如下:

1. 修正submitForm的参数接收逻辑

Form组件中,submitForm函数的第二个参数{handleSubmit}是无效的——React表单的onSubmit回调只会传入事件对象e,不会自动传递props。你需要从组件的props中获取handleSubmit:

修改Form组件的定义,直接解构props拿到handleSubmit:

function Form({ handleSubmit }) {
    const [name, setName] = useState("");
    const [job, setJob] = useState("");

    const submitForm = (e) => { // 仅接收事件对象e
        e.preventDefault();
        // ...后续逻辑
    }

    // ...return部分不变
}

2. 优化新数据的创建(可选但更可靠)

你已经通过useState维护了name和job的状态,没必要再从e.target取值,直接用state的值更能保证数据一致性:

const submitForm = (e) => {
    e.preventDefault();
    const newChar = {
        name: name,
        job: job
    }
    handleSubmit(newChar);
    setName('');
    setJob('');
}

修改后的完整Form.js代码

import { useState } from "react";

function Form({ handleSubmit }) {
    const [name, setName] = useState("");
    const [job, setJob] = useState("");

    const submitForm = (e) => {
        e.preventDefault();
        const newChar = {
            name: name,
            job: job
        }
        handleSubmit(newChar);
        setName('');
        setJob('');
    }

    return (
    <form onSubmit={submitForm}>
      <label htmlFor="name">Name</label>
      <input
        type="text"
        name="name"
        id="name"
        value={name}
        onChange={(e) => setName(e.target.value)} />
      <label htmlFor="job">Job</label>
      <input
        type="text"
        name="job"
        id="job"
        value={job}
        onChange={(e) => setJob(e.target.value)} />
      <input type="submit"/>  
    </form>
  );
}

export default Form;

额外提示(关于删除功能)

你的removeChar函数用characters.indexOf(character) !== id来过滤,虽然能工作,但如果数组中有重复元素会出问题。建议给每个字符对象添加唯一id,比如:

// App.js的初始state
const [characters, setCharacters] = useState([
  { id: 1, name: 'Charlie', job: 'Janitor' },
  { id: 2, name: 'Mac', job: 'Bouncer' },
  { id: 3, name: 'Dee', job: 'Aspring actress' },
  { id: 4, name: 'Dennis', job: 'Bartender' },
]);

// 修改removeChar
const removeChar = (id) => {
  const newChars = characters.filter(character => character.id !== id);
  setCharacters(newChars);
}

这样删除逻辑会更健壮,避免因为重复元素导致的错误。

内容的提问来源于stack exchange,提问作者Sofia Lazrak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:35:09