将mutableState传递给可组合函数是否最佳?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月27日 21:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定