英文:
Is passing mutablestate to composable function optimal?
问题
这是:
@Composable
fun TextEdit(textState: MutableState<String>) {
val text by textState
TextField(onValueChange = {
text = it
}, value = text)
}
对于不必要的重新组合是否是最佳的?
英文:
Like this :
@Composable
fun TextEdit(textState: MutableState<String>) {
val text by textState
TextField(onValueChange = {
text = it
}, value = text)
}
Is it optimal for unnecessary recompositions?
答案1
得分: 1
这仍然会触发不必要的重新组合,而不是尝试使用**状态提升**的概念,其中您的代码应为:
@Composable
fun TextEdit(textState: String) {
TextField(onValueChange = {
textState = it
}, value = textState)
}
以下是要遵循的最佳实践:
您应该将UI状态提升到所有读取和写入它的可组合项之间的最低共同祖先。您应该将状态保持最接近其被使用的位置。从状态所有者向使用者暴露不可变状态和修改状态的事件。
最低共同祖先也可以在组合之外。例如,当在ViewModel中提升状态时,因为涉及到业务逻辑。
英文:
That will still trigger unnecessary recompositions, instead try using the concept of state hoisting where your code should be:
@Composable
fun TextEdit(textState: String) {
TextField(onValueChange = {
textState = it
}, value = textState)
}
Here is the Best Practice to follow:
> You should hoist UI state to the lowest common ancestor between all
> the composables that read and write it. You should keep state closest
> to where it is consumed. From the state owner, expose to consumers
> immutable state and events to modify the state.
>
> The lowest common ancestor can also be outside of the Composition. For
> example, when hoisting state in a ViewModel because business logic is
> involved.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论