在React中使用Immutable.js以实现历史记录/“回溯时间”功能时,可以采用哪些模式?为了理解这些问题,我构建了一个简单的React应用程序,它显示一个随机数并提供三个按钮:
这是GUI:
这是我的代码:
const React = require('react');
import {List} from 'immutable';
import {assert} from 'chai';
const App = React.createClass({
getInitialState: function() {
return {
history: List([Math.random()]),
currentTime: 0,
maxTimeReached: 0
};
}
, newRandomNumber() {
const newHistory = this.state.history.push(Math.random());
this.setState({history: newHistory
, currentTime: this.state.currentTime+1
, maxTimeReached: this.state.maxTimeReached+1
});
}
, backInTime() {
this.setState({currentTime: this.state.currentTime-1});
}
, forwardInTime() {
this.setState({currentTime: this.state.currentTime+1});
}
, componentWillUpdate(_, nextState) {
// sanity checks
assert.isTrue(nextState.currentTime>=0);
assert.isTrue(nextState.currentTime<=nextState.maxTimeReached);
}
, render: function() {
return (
<div>
<div>{this.state.history.get(this.state.currentTime)}</div>
<div>
<button onClick={this.newRandomNumber}
disabled={this.state.currentTime<this.state.maxTimeReached}>new random
</button>
</div>
<div>
<button onClick={this.backInTime}
disabled={this.state.currentTime==0}><
</button>
<button onClick={this.forwardInTime}
disabled={this.state.currentTime===this.state.maxTimeReached}> >
</button>
</div>
</div>
);
}
});
export default App;
我的问题是:
this.props.state
中或作为该类的成员属性,