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

喜欢的东西:

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

我试过:

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

这:

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

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


当前回答

试试这个:

const { jasper } = this.state; //Gets the object from state
jasper.name = 'A new name'; //do whatever you want with the object
this.setState({jasper}); //Replace the object in state

其他回答

舰队指挥官:样品

   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 }
    
        })
      }

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

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

试试这个,应该没问题

this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));

创建一个状态对象

this.state = {
  objName: {
    propertyOne: "",
    propertyTwo: ""
  }
};

使用setState更新状态

this.setState(prevState => ({
  objName: {
    ...prevState.objName,
    propertyOne: "Updated Value",
    propertyTwo: "Updated value"
  }
}));

通过使用input html的input name属性,我们可以有一个更动态的方法来更新对象属性。

DOM HTML输入名称属性

<input type="text" name="fname" handleChange={(e: any) => { updatePerson(e) }}/>
<input type="text" name="lname" handleChange={(e: any) => { updatePerson(e) }}/>

React / TSX object.assign

const [person, setPerson] = useState<IPerson>({});

   function updatePerson(e: React.ChangeEvent<HTMLInputElement>): void {
        const { name, value } = e.currentTarget;

        setPerson(prevState => {
            const newState = Object.assign(person, { [name]: value })
            return { ...prevState, ...newState };
        });
    }