[英]Why is SetState in React updating other objects in handler?
在onChange事件處理程序中,我僅在userTxt上進行setState()調用,但看起來它還設置了顏色對象的狀態。 對我來說奇怪的是,這僅發生在顏色對象上,而沒有發生在年齡變量上。
想知道是否有人可以解釋為什么會這樣嗎? 這是我的webpackbin示例的鏈接。 在輸入中寫入時,顏色對象上的狀態會更改。 。
我希望有人可以向我解釋為什么會這樣。 提前非常感謝您。
import React, { Component } from 'react';
export default class Hello extends Component {
constructor() {
super();
this.handleMe = this.handleMe.bind(this);
this.state = {
age: 21,
colors: {
best: 'blue',
second: 'green'
},
userTxt: ""
}
}
handleMe(e) {
let myAge = this.state.age;
let myColors = this.state.colors;
myAge = myAge + 1;
myColors['best'] = 'mistyrose';
myColors['second'] = 'red';
this.setState({ userTxt: e.target.value });
}
render() {
const { age, colors, userTxt} = this.state;
return (
<div>
<form action="">
<input type="text"onChange={this.handleMe}/>
<div>Age: {age}</div>
<div>Colors - best: {colors.best}</div>
<div>Colors - second: {colors.second}</div>
<div>UserTxt: {userTxt}</div>
</form>
</div>
)
}
}[enter link description here][1]
[1]: https://www.webpackbin.com/bins/-KvFx-s7PpQMxLH0kg7m
發生這種情況是因為您直接在這里操縱狀態。 myColors引用狀態的顏色對象。
handleMe(e) {
let myAge = this.state.age;
let myColors = this.state.colors;
myAge = myAge + 1;
//directly mutating the state with these 2 lines.
myColors['best'] = 'mistyrose';
myColors['second'] = 'red';
this.setState({ userTxt: e.target.value });
}
您需要制作this.state.colors的副本,例如讓myColors = Object.assign({},this.state.colors)
狀態中的顏色字段是作為參考存儲的對象。 年齡字段是一個整數,並存儲為原始值。
將顏色字段分配給myColors時,兩個變量都引用同一對象。 因此,當您更新myColors時,狀態中的顏色字段將被更新。
當您將年齡字段分配給myAge時,它將狀態中的年齡字段的值復制到myAge字段。 因此,當您更新myAge時,它不會更新狀態。
為避免這種意外的副作用,您應該創建一個新對象並將顏色值從狀態復制到該對象。 您可以使用
let myColors = {...this.state.colors};
聲明變量時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.