javascript - 在 setState 中使用变量 - react

标签 javascript reactjs

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

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 没有改变?

最佳答案

发生这种情况是因为在 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)})
  }
}

关于javascript - 在 setState 中使用变量 - react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304398/

相关文章:

javascript - 将事件类添加到 href

javascript - 仅显示所选选项的值

javascript - 警告 : validateDOMNesting(. ..) : <body> cannot appear as a child of <div> in React. js

node.js - 事件.js :183 throw er;//Unhandled 'error' event

javascript - React 如何协同添加和删除工作?

javascript - 如果不知道索引值,如何通过索引从数组中删除项目?

javascript - 带提示的两个数字的总和

node.js - 页面渲染速度快于我的数据获取速度

reactjs - 通过 Redux 获取数据后应用程序重新启动

javascript - "Remove"评估为 true 时的测试条件