如何从e.target.name更新状态中的对象

时间:2019-10-07 13:49:44

标签: javascript reactjs

我正在尝试从这样的表单中输入数据-

<h1>Company Position</h1>
<input
    name="company.position"
    type="text"
    onChange={(e) => functions.setData(e)}
    value={data.company.position}
/>

进入这样的状态对象-

const [ form, setValues ] = useState({
    name        : 'Jo Smith',
    email       : 'JoSmith@domain.com',
    phone       : null,
    company     : {
        name     : null,
        position : null
    }
});

在我传递目标的地方使用handleStateChange函数

const handleStateChange = (e) => {
    e.preventDefault();
    setValues({
        ...form,
        [e.target.name]: e.target.value
    });
};

我似乎无法在内部状态下更新company对象,因为我认为该对象可以将company.name识别为目标名称。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

e.target.namecompany.position,您不能设置obj["company.position"]之类的嵌套属性,必须将其拆分:

<input
  name="company.position"
  type="text"
  onChange={e => functions.setData(e)}
  value={data.company.position}
/>;

const handleStateChange = e => {
  e.preventDefault();
  const [section, key] = e.target.name.split(".");

  // section is : company
  // key is : position

  if (key) {
    // if you have nested keys to update
    setValues({
      ...form,
      [section]: {
        ...form[section],
        [key]: e.target.value
      }
    });
  } else {
    // if you're updating on the first level
    setValues({
      ...form,
      [section]: e.target.value
    });
  }
};

答案 1 :(得分:0)

const nested = e.target.name.split(".");
    const [section, key] = nested; 
     if(nested.length > 2){
        let total = nested.length;
        let ultimo = nested[total-1];
        saveclinicHistory({
            ...clinicHistory,
            [section]: {//patient
                ...clinicHistory[section],
                [key]: {//address
                    ...clinicHistory[section][key],
                    [ultimo]:e.target.value

                }
            }
        });