Javascript 反应:在状态更改后获取initialstate
是否可以在状态更改后检索初始状态?例如:Javascript 反应:在状态更改后获取initialstate,javascript,reactjs,Javascript,Reactjs,是否可以在状态更改后检索初始状态?例如: React.createClass({ getInitialState: function() { return { foo: 'bar' } }, componentWillMount: function() { this.setState({ foo: 'foo' }) }, componentDidMount: function() { // get the initial state "bar" ?
React.createClass({
getInitialState: function() {
return { foo: 'bar' }
},
componentWillMount: function() {
this.setState({ foo: 'foo' })
},
componentDidMount: function() {
// get the initial state "bar" ?
}
})
我在文件里找不到任何东西。我当然可以将该值保存在外部变量中,但如果可以将initialstate视为可重复使用的“config”对象,我只是好奇而已。不,初始状态没有存储,但可以调用
this.getInitialState()
如果要重新执行该函数。只需将初始状态保存在变量中:
React.createClass({
initialState: { foo: 'bar' },
getInitialState : function () {
return this.initialState;
},
componentWillMount: function () {
this.setState({ foo: 'foo' })
},
componentDidMount : function () {
console.log(this.initialState.foo); // Logs 'bar'
}
});