我的界面代码依赖于许多连续步骤,例如:
getData()
.then( ( data ) => this.updateHistory(data) )
.then( this.changeInterface )
像this.updateHistory和this.changeInterface这样的函数会更改状态。
我知道this.setState接受回调,因此在这些函数中,我会做类似的事情:
updateHistory(data){
this.setState( {new: data}, ( callback ) => {
this.props.dispatch( updateRelevantRedux() )
.then( () => doAnotherImportantThing() )
.then( () => {
const important = createImportant()
if ( important > 99 ) this.setState( { essential: important } )
} )
} )
}
但是,这通常导致难以阅读类似于回调地狱的代码。我希望能够致电this.setState作为对我的承诺:
例如:
updateHistory(data){
return this.setState( { new: data } )
.then( () => this.props.dispatch( updateRelevantRedux() ) )
.then( () => doAnotherImportantThing() )
.then( () => {
const important = createImportant()
if ( important > 99 ) return this.setState( { essential: important } )
} )
}
答案 0 :(得分:-3)
您可以利用回调功能来创建setState函数的promise版本。例如,在您的类构造函数中,您可以像这样创建一个promise友好的setState:
this.promiseState = state => new Promise( resolve => this.setState( state, resolve ) )
或者用不太简洁的js编写:
this.promiseState = ( state ) => {
return new Promise( ( resolve ) => {
this.setState( state, resolve )
} )
}
哪些es2017 +写作版本是
this.promiseState = function ( state ) {
return new Promise( function ( resolve, reject ) {
this.setState( state, function() {
resolve()
} )
} )
}