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