Javascript 如何动态(通过路径)更新React state属性

Javascript 如何动态(通过路径)更新React state属性,javascript,object,Javascript,Object,我正在尝试使用路径更改react状态下的属性值: handleChange = (e, path) => { e.persist(); let newState = this.state || {}; (newState[path] || {})[e.target.name] = e.target.value; this.setState(newState); } 问题是,newState[path]未定义,而键入的路径工作正常 console.log(

我正在尝试使用路径更改react状态下的属性值:

handleChange = (e, path) => {
    e.persist();

    let newState = this.state || {};
    (newState[path] || {})[e.target.name] = e.target.value;
    this.setState(newState);
}
问题是,newState[path]未定义,而键入的路径工作正常

console.log(path); //form.section[0]
console.log(newState[path]); //undefined
console.log(newState.form.section[0]); { type: "person", gender: "female", ... }

有人能帮我吗?

newState
没有名为“form.section[0]”的属性,这是您在编写
newState[path]
时试图访问的属性
newState
确实有一个名为“form”的属性,这是一个具有名为“section”属性的对象(这是一个数组)。这就是为什么编写
newState.form.section[0]
会得到想要的结果


您可能应该使用这里提到的
lodash.get
:将
newState[path]
计算为
newState[form.section[0]]
,这取决于
form.section[0]
的值,例如,如果
form.section[0]=='john'
,那么您将得到未定义的
newState.john

它与
newState.form.section[0]
不同,后者实际上是
newState['form']['section']['0']
。这是一个更纯粹的JS问题,而不是一个反应问题

如果没有更多关于组件其余部分的上下文,我的建议是简化提供给
handleChange
处理程序的
路径。只需使用唯一的字段id,而不是复合路径。那么代码可能是这样的:

handleChange = (e, fieldId) => {

  //...

  this.setState({
    [fieldId]: e.target.value
  })
} 

试试console.log(newState[`${path}`])@MuhammadZeeshan仍然没有定义