是否有可能更新对象的属性与setState?

喜欢的东西:

this.state = {
   jasper: { name: 'jasper', age: 28 },
}

我试过:

this.setState({jasper.name: 'someOtherName'});

这:

this.setState({jasper: {name: 'someothername'}})

第一个会导致语法错误,第二个则什么都不做。什么好主意吗?


当前回答

舰队指挥官:样品

   const [formData, setformData] = useState({
           project_admin_permissions: {
              task_forms: false,
              auto_assign_rules: false,
              project_notes: true,
              alerts: false,
              update_criteria: true,
              project_flow: false,
              reports: false,
            }
        
          })
    
     const handleChangeCheckBox = (e) => {
       setformData({
          ...formData, project_admin_permissions: { ...formData.project_admin_permissions, [e.target.name]: e.target.checked }
    
        })
      }

其他回答

同样,按照Alberto Piras解决方案,如果你不想复制所有的“state”对象:

handleChange(el) {
    let inputName = el.target.name;
    let inputValue = el.target.value;

    let jasperCopy = Object.assign({}, this.state.jasper);
    jasperCopy[inputName].name = inputValue;

    this.setState({jasper: jasperCopy});
  }

这里使用展开运算符和一些ES6

this.setState({
    jasper: {
          ...this.state.jasper,
          name: 'something'
    }
})

舰队指挥官:样品

   const [formData, setformData] = useState({
           project_admin_permissions: {
              task_forms: false,
              auto_assign_rules: false,
              project_notes: true,
              alerts: false,
              update_criteria: true,
              project_flow: false,
              reports: false,
            }
        
          })
    
     const handleChangeCheckBox = (e) => {
       setformData({
          ...formData, project_admin_permissions: { ...formData.project_admin_permissions, [e.target.name]: e.target.checked }
    
        })
      }

不使用异步和等待使用此…

funCall(){    
     this.setState({...this.state.jasper, name: 'someothername'});
}

如果你使用异步和等待使用这个…

async funCall(){
      await this.setState({...this.state.jasper, name: 'someothername'});
}

这是最快和最易读的方式:

this.setState({...this.state.jasper, name: 'someothername'});

即使this.state.jasper已经包含了name属性,也会使用新名称name: 'someothername'。