英文:
Preformance in jetpackCompose
问题
I understand your request. Here's the translated code:
正如您在代码中所看到的,我有两个可组合函数,分别命名为 Screen 和 Body。
当 showError 的状态更改时,body 函数也会重新组合。这会产生任何副作用吗?如果是的话,如何避免这种重新组合。
@Composable
fun Screen(viewModel: ViewModel) {
val state by viewModel.uiState.collectAsState()
if (state.showError) {
Text("示例视图")
}
Body(state = state)
}
@Composable
fun Body(state: UiState) {
// 待办事项
}
Please note that I've translated the code part, as you requested, and didn't include any additional content. If you have any further questions or requests, feel free to ask.
英文:
As you can see in the code, I have two composable functions named Screen and Body.
When the state of the showError changes, the body function is also recompose. Does it have any side effect? If yes, how to avoid this recompose.
@Composable
fun Screen(viewModel: ViewModel) {
val state by viewModel.uiState.collectAsState()
if (state.showError) {
Text("sample view")
}
Body(state = state)
}
@Composable
fun Body(state: UiState) {
// todo
}
答案1
得分: 1
这是compose
函数的默认行为。每当观察到状态由于状态值的任何更改而发生变化时,函数会重新组合并显示更新后的值。所以,是的,当使用可组合函数时,有一些事情你可能需要确保,比如,如果你在可组合函数中声明一个变量,然后稍后更新该变量,那么在函数重新组合时,该变量的值将返回到默认状态。
为避免重新组合:我认为在使用状态变量或remember
函数时,特别是不太可能实现,但你可以尽量减少所需的重新组合次数。
以下是有关其生命周期如何运作的参考链接:
https://developer.android.com/jetpack/compose/lifecycle
英文:
This is the default behaviour of the compose function. Whenever a state is observed due to any change in state value, the function recomposes and displays the updated values. So, yeah there are things that you may need to make sure when using the composable functions like for example, if you are declaring a variable in a composable function and that variable is later updated then that variable's value will go in default state when function is recomposed.
To avoid recomposition: I do not think that is possible specially when you are using state variables or remember functions but what you can do is minimise the recompositions needed.
Below is a reference on how its lifecycle works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论