简体   繁体   中英

mutableStateOf holding the value after the recomposition without remember API in Jetpack Compose

Any time a state is updated a recomposition takes place.

but here, I haven't used the remember API, but after the recomposition also it's holding the value, is the mutableStateOf() will remember the value without remember API?

@Composable
fun MyChildUI() {

    var count by mutableStateOf(1)

    Button(onClick = {
        count++
        println(count)
    }) {
        Text(text = "$count")
    }
}

图像

In this particular example when you click the button, only lines 42-47 will be recomposed. You can verify this by adding a log statement in line 41.

When the whole MyChildUI composable recomposes, the value of the count will be reset to 1.

So, you should use remember to avoid issues.

This is because of scoped recomposition. Any Composable that is not inline and returns Unit is a scope. Compose only triggers recomposition in nearest scope. In your example it's Button's scope. You can check out this question which is very similar

Why does mutableStateOf without remember work sometimes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM