反应状态。更改

时间:2018-01-05 14:27:18

标签: javascript reactjs

更改状态有问题。我有一些州=

id: '',
avatar: '',
steps: 0,
programName: '',
programDate: '',
programPrice: '',
personalInfo: {
  name: '',
  surname: '',
  sex: 'man',
  birthDay: '',
  birthMonth: '',
  birthYear: '',
  familyStatus: '',
  countryBirth: '',
  cityBirth: '',
  birthCitizenship: '',
  currentCitizenship: ''
},

我如何改变这个属性:this.state.personalInfo.name ??

2 个答案:

答案 0 :(得分:0)

使用setState()方法更改 状态。

this.setState({this.state.personalInfo.name:"new data"});

See more here

https://www.tutorialspoint.com/react_native/react_native_state.htm

答案 1 :(得分:0)

这个问题可能会重复。

要更改组件状态中嵌套对象的值,正确的方法是:

const { personalInfo } = this.state;
this.setState({
  ...this.state,
  personalInfo: {
    ...personalInfo,
    name: 'New Name',
  },
});

每次更改状态时,都必须考虑setState()函数需要一个新对象。扩展运算符(...)在创建新对象时很有用。所以基本上你必须复制先前状态的属性并替换personalInfo的名称属性。