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