2017-05-03 22 views
0

在反應文檔瀏覽:陣營,科特林包裝的setState方法

https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

它說,下面的代碼是不安全的使用,因爲狀態是異步更新:

this.setState({ 
    counter: this.state.counter + this.props.increment, 
}); 

,而是以通過之前的狀態和道具如下:

this.setState(function(prevState, props) { 
    return { 
    counter: prevState.counter + props.increment 
    }; 
}); 

但是,做出反應,科特林包裝設在這裏:

https://github.com/Kotlin/kotlin-fullstack-sample/tree/master/frontend/src/org/jetbrains/react

已通過作爲國家的一個擴展功能,修改狀態對象的變量的狀態變化:

//Located in the ReactComponent class in ReactComponent.kt 
fun setState(builder: S.() -> Unit) { 
    ... 
} 

如果我叫setState功能像這樣在科特林:

setState { 
    counter: state.counter + props.increment 
} 

是不是等同於上述不安全的方法? React-Kotlin包裝器中是否需要這樣執行?

fun setState(builder: S.(prevState: S, props: P) -> Unit) { 
    ... 
} 

然後這樣調用?

setState { prevState, props -> 
    counter: prevState.counter + props.increment 
} 

回答

0

如果你想得到一個setState的結果,那麼你必須調用setState(newState,callback)。

也許,這個React綁定不僅僅是一個包裝反應。我認爲,這個反應是真實反應的真面目。