gpt4 book ai didi

android - Android Jetpack Compose 中数据类的更新策略

转载 作者:行者123 更新时间:2023-12-05 06:09:39 25 4
gpt4 key购买 nike

我尝试使用数据类中的对象来更新 Composable 并将其声明如下:

data class CounterState(var counter: Int = 0)
.....
val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }

structuralEqualityPolicy() 是 Composable 的更新策略,定义如下:

A policy to treat values of a MutableState as equivalent if they arestructurally (==) equal.

如果属性计数器发生如下变化:counterState.counter++ 应该更新可组合项,但这不起作用。

我使用 Compose 版本 1.0.0-alpha06

知道如何解决这个问题吗?

import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.runtime.*
import androidx.ui.tooling.preview.Preview

data class CounterState(var counter: Int = 0)

@Composable
fun dataClassRemember() {
val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }
Column() {
Button(onClick = {
counterState.counter++
}) {
Text(text = "Increment")
}
Text(text = "Counter value is ${counterState.counter}")
}
}

@Preview("dataClassRemember")
@Composable
fun dataClassRememberPreview() {
dataClassRemember()
}

最佳答案

我会试试这个:

data class CounterState(var counter: Int by remember { mutableStateOf(0)})

希望有用安娜

关于android - Android Jetpack Compose 中数据类的更新策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64699135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com