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

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


<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.name 识别为目标名称。


任何帮助,将不胜感激。


慕桂英3389331
浏览 225回答 2
2回答

幕布斯6054654

e.target.name是company.position,您不能设置嵌套属性,例如obj["company.position"],您必须将其拆分:<input&nbsp; name="company.position"&nbsp; type="text"&nbsp; onChange={e => functions.setData(e)}&nbsp; value={data.company.position}/>;const handleStateChange = e => {&nbsp; e.preventDefault();&nbsp; const [section, key] = e.target.name.split(".");&nbsp; // section is : company&nbsp; // key is : position&nbsp; if (key) {&nbsp; &nbsp; // if you have nested keys to update&nbsp; &nbsp; setValues({&nbsp; &nbsp; &nbsp; ...form,&nbsp; &nbsp; &nbsp; [section]: {&nbsp; &nbsp; &nbsp; &nbsp; ...form[section],&nbsp; &nbsp; &nbsp; &nbsp; [key]: e.target.value&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; } else {&nbsp; &nbsp; // if you're updating on the first level&nbsp; &nbsp; setValues({&nbsp; &nbsp; &nbsp; ...form,&nbsp; &nbsp; &nbsp; [section]: e.target.value&nbsp; &nbsp; });&nbsp; }};

摇曳的蔷薇

const nested = e.target.name.split(".");&nbsp; &nbsp; const [section, key] = nested;&nbsp;&nbsp; &nbsp; &nbsp;if(nested.length > 2){&nbsp; &nbsp; &nbsp; &nbsp; let total = nested.length;&nbsp; &nbsp; &nbsp; &nbsp; let ultimo = nested[total-1];&nbsp; &nbsp; &nbsp; &nbsp; saveclinicHistory({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...clinicHistory,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [section]: {//patient&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...clinicHistory[section],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [key]: {//address&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...clinicHistory[section][key],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ultimo]:e.target.value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript