我需要從this.state
複製對象以更改其某些屬性值。對象是否通過引用破壞工作或克隆對象
例如,在下面的方法狀態被直接(this.state.errors = {}
)
authorFormIsValid =() => {
var formIsValid = true;
this.state.errors = {}; //clear any previous errors.
if (this.state.author.firstName.length < 3) {
this.state.errors.firstName = 'First name must be at least 3 characters.';
formIsValid = false;
}
if (this.state.author.lastName.length < 3) {
this.state.errors.lastName = 'Last name must be at least 3 characters.';
formIsValid = false;
}
this.setState({errors: this.state.errors});
return formIsValid;
};
突變爲了避免這種情況,我知道,我們可以使用:
一)
let errors={...this.state.errors};
let errors=Object.assign({},this.state.errors);
但有時候我似乎有些例子,其中object destructuring
它這樣使用:
authorFormIsValid =() => {
let formIsValid = true;
//Destructuring error and authors from this.state
let {errors, author} = this.state;
errors = {}; //clear any previous errors.
if (author.firstName.length < 3) {
errors.firstName = 'First name must be at least 3 characters.';
formIsValid = false;
}
if (author.lastName.length < 3) {
errors.lastName = 'Last name must be at least 3 characters.';
formIsValid = false;
}
this.setState({errors});
return formIsValid;
};
所以我的問題是,是否object destructuring
等同於上面提到的其他兩種方法?我的意思是,我是否會避免直接使用簡單的object destructuring
來突變狀態?
所以我想我必須堅持使用對象擴展運算符或Object.assign,對吧? – eddy
是的,我建議你和Spread運營商一起考慮Redux文檔也推薦它。看到這個答案https://stackoverflow.com/questions/43376849/using-object-assign-in-react-redux-is-a-good-practice/43376980#43376980 –