在setState中使用变量-反应

用户名

我知道之前也曾问过类似的问题,但是如果我不想将整个状态(仅其属性之一)设置为变量,该怎么办?像这样:

var initialProperty = {
  name: '',
  id: 0,
  type: ''
}

class Example extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      otherProperty: '',
      targetProperty: initialProperty
      //at the start of the Component, everything works fine.
      //the targetproperty is set to initialproperty
    }
  }
  //by the time, the targetproperty was changed from the initial in the component
  //but if i click a button, i want to set targetproperty to the initialproperty
  somethingHappensOnClick = () => {
    this.setState({targetProperty: initialProperty})
    //unfortunately, the targetproperty wasn't set to the initial.
  }
}

难道我做错了什么?为什么targetProperty不改变?

玛雅·舒克拉(Mayank Shukla)

发生这种情况是因为在js数组和对象中通过引用复制。所以当你设定

targetProperty: initialProperty

targetProperty将获得的引用initialProperty,并且您将对所做的所有更改也targetProperty将被应用initialProperty

想法是,每次创建一个新对象,而不是复制引用。

这样写:

var initialProperty = {
  name: '',
  id: 0,
  type: ''
}

class Example extendds React.Component{
  constructor(props){
    super(props);
    this.state = {
      otherProperty: '',
      targetProperty: Object.assign({}, initialProperty) // or {...initialProperty}
    }
  }

  somethingHappensOnClick = () => {
    this.setState({targetProperty: Object.assign({}, initialProperty)})
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章