我完全新手到ReactJS並沒有當我創建了一個有些奇怪的行爲反應用ReactJS在狀態ES6類:改變只有一次
https://jsfiddle.net/8f5tqr74/2/
class CounterViewModel {
constructor() {
this.value = 5;
}
tick() {
//cannot move logic of this method to sendTick complex logic will be here
this.value++;
}
}
var Counter = React.createClass({
getInitialState: function() {
return new CounterViewModel();
},
sendTick: function() {
console.log("Before:",this.state);
var stateObj = this.state;
stateObj.tick();
this.setState(stateObj);
console.log("After:",this.state);
},
render: function() {
return <div>
{this.state.value}
<button onClick={this.sendTick}>Increase</button>
</div>
}
});
ReactDOM.render(<Counter />, document.getElementById('container'));
我的問題是 此代碼工作當我點擊按鈕 只有我第一次得到這個開發者控制檯
//first click
Before: CounterViewModel {value: 5}
After: CounterViewModel {value: 6}
//second click
Before: Object {value: 6}
在第二次點擊後CLAS狀態s是刷新到對象,但我沒有在這個對象使操作
我的問題是:
1)爲什麼的setState後作出反應沖洗類對象的?
2)爲什麼在getInitialState後沒有React flush類對象?
3)如何將複雜的邏輯放入React中的狀態對象?我知道我可以重新創建對象,具有更高的價值和一切都將正常工作(見下面的代碼)
class CounterViewModel {
constructor(value) {
this.value = value;
}
}
var Counter = React.createClass({
getInitialState: function() {
return new CounterViewModel(5);
},
sendTick: function() {
this.setState(new CounterViewModel(this.state.value+1))
},
render: function() {
return <div>
{this.state.value}
<button onClick={this.sendTick}>Increase</button>
</div>
}
});
ReactDOM.render(<Counter />, document.getElementById('container'));
我建議您不要將可變計數器實例直接存儲在組件狀態中。相反,只需將計數器的「value」屬性複製到組件狀態 – naomik
即可!但是這不符合第三個問題:「我怎樣才能把複雜的邏輯放入React中的狀態對象中:-P – QoP