Jetpack Compose官方示例代码中updateSection变量的赋值内容是什么?
解答
updateSection 不会被赋值为 tabContent.first().content,它是 Compose 状态对象自带的状态更新函数。
你搞错了解构声明的作用对象:这行代码的解构是作用在 rememberSaveable { mutableStateOf(...) } 的返回值上,不是作用在 TabContent 实例上。
Jetpack Compose 中 mutableStateOf() 返回的是 MutableState<T> 类型实例,Kotlin 解构可以直接用在该类型上,因为官方对它做了运算符重载:
- 第一个解构值
component1()对应状态的当前值,也就是你拿到的currentSection,初始值就是传入的tabContent.first().section - 第二个解构值
component2()对应状态更新函数,传入新值即可修改状态,这就是updateSection的实际值,类型为(Sections) -> Unit。
可以用等价写法来直观对比:
// 你写的解构写法 val (currentSection, updateSection) = rememberSaveable { mutableStateOf(tabContent.first().section) } // 等价的普通写法 val state = rememberSaveable { mutableStateOf(tabContent.first().section) } val currentSection = state.value val updateSection = { newSection: Sections -> state.value = newSection }
只有当你直接对 TabContent 实例做解构时,才会拿到它的 section 和 content 属性,比如 val (section, content) = tabContent.first(),和你问题里的解构逻辑完全不相关。
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

