TypeError: can't define array index property past the end of an array with non-writable length

TypeError: can't define array index property past the end of an array with non-writable length

我正在通过动态添加表单字段来更新表单状态,但是出现了这个错误 我试过的 应该发生的是,如果我想要的话,应该在点击时将更多字段添加到每个子字段

const addExperience = () => {
    let temp = Object.assign({}, form);
    temp.experience.push({
      company: "",
      position: "",
      startDate: "",
      endDate: "",
      description: "",
    });
    setForm(temp);
  }

这是表格

const [form, setForm] = useState({
    name: "adarsh raj",
    email: "adarsh@gmail.com",
    phone: "83404dvsdsd",
    address: "patel chowk",
    city: "deoghar",
    education: [
      {
        school: "dav ",
        major: "intermediate",
        GPA: "8.12",
      },
    ],
    experience: [
      {
        company: "venturepact llc",
        position: "associate software developer",
        startDate: "dd-mm-yyyy",
        endDate: "dd-mm-yyyy",
        description: "description",
      },
    ],
    projects: [
      {
        projectName: "project name",
        projectDescription: "project description",
      },
    ],
    skills: [
      {
        skillName: "your skill name",
      },
    ],
  });

像这样的代码应该可以工作。但是要进行测试,您可以尝试以下语法:

  const addExperience = () => {
    let temp = Object.assign({}, form);
    temp.experience = [
      ...temp.experience,
      {
        company: "",
        position: "",
        startDate: "",
        endDate: "",
        description: ""
      }
    ];
    setForm(temp);
  };

Object.assign(target, source) 只是浅拷贝。

useState return 值为 Immutable;

参考下面的demo

var x = new Array(10).fill(0);
Object.freeze(x);
x.push(11) // same error 

您可以通过deep copying或重新分配first layer的经验来解决这个问题。

因为使用了浅拷贝,只能赋值第一层。如果问题属性出现在二级,则无法解决。所以不推荐这种方式,推荐深拷贝。

let temp = JSON.parse(JSON.stringify(form));
let temp = lodash.cloneDeep(form);// need install lodash