Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React Kotlin包装器设置状态方法_Kotlin - Fatal编程技术网

React Kotlin包装器设置状态方法

React Kotlin包装器设置状态方法,kotlin,Kotlin,在此处的react文档上: 它表示以下代码使用起来不安全,因为状态是异步更新的: this.setState({ counter: this.state.counter + this.props.increment, }); 而不是像这样通过前一个状态和道具: this.setState(function(prevState, props) { return { counter: prevState.counter + props.increment }; }); 但是

在此处的react文档上:

它表示以下代码使用起来不安全,因为状态是异步更新的:

this.setState({
  counter: this.state.counter + this.props.increment,
});
而不是像这样通过前一个状态和道具:

this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});
但是,React Kotlin包装器位于以下位置:

是否将状态更改作为状态的扩展函数传入,该扩展函数修改状态对象上的变量:

//Located in the ReactComponent class in ReactComponent.kt
fun setState(builder: S.() -> Unit) {
    ...
}
如果我在Kotlin中调用
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
}

如果要获取setState的结果,则必须调用setState(newState,callback)


很可能,这个React绑定不仅仅是一个wrapper-over-React。我认为react是真实react之上的一个门面。

如果您查看create react kotlin应用程序源代码,您将在setState调用之前找到以下注释: “实际上,该操作是在状态的副本上执行的,因此它实际上保持不变”

就是这样,kotlin复制状态并将copy作为接收方传递给setState方法。因此,您应该编写“counter=counter+props.increment”,而不是“counter:state.counter+props.increment”