android - _uiState.value = uiState.value.copy() 不会导致重组

标签 android kotlin state android-jetpack-compose viewmodel

我的代码出现了一些 Unresolved 情况, 我的目标是更改“设备”列表中项目的属性(更新 bool 值), 更改应该会导致 View 重组,但这并没有发生, 此外,我可以看到该项目确实随调试器而更改,但它也会导致添加一个附加项目(没有包含更改的旧副本)以显示在我的列表中。

你知道我的新值分配是怎么错的吗?

View 模型

private val _uiState = mutableStateOf(BTPairingState())
val uiState: State<BTPairingState> get() = _uiState 

这就是我编辑列表中项目的方式

    if (handlerDeviceResponse.status != null) {            
        viewModelScope.launch {
            uiState.value.devices.find { it.macAddress == handlerDeviceResponse.device.macAddress }?.isConnected = handlerDeviceResponse.status
            _uiState.value = uiState.value.copy()
        }
    }

BT配对状态:

data class BTPairingState (
    val devices: MutableList<BtDeviceItemUiModel> = mutableListOf(),
    val deviceType: DeviceType = DeviceType.RFID,
)

数据类

data class BtDeviceItemUiModel(
    val name: String,
    val macAddress : String,
    var isConnected: Boolean = false
)

屏幕:

@Destination
@Composable
fun BTPairScreen(
    viewModel: BTPairViewModel = hiltViewModel(),
) {

    val state = viewModel.uiState
    BTPairDevices(state.value.devices) { viewModel.deviceItemClicked(it) }


最佳答案

替换var isConnected通过val isConnected .

然后,替换 val devices: MutableList<BtDeviceItemUiModel> = mutableListOf()通过val devices: List<BtDeviceItemUiModel> = emptyList() .

IOW,停止在您的状态内部使用可变值。

然后,您可以修改代码以更新您的 MutableState具有新值,使用类似:

    if (handlerDeviceResponse.status != null) {            
            val newDevices = uiState.value.devices.map { device ->
              if (device.macAddress == handlerDeviceResponse.device.macAddress) {
                device.copy(isConnected = handlerDeviceResponse.status)
              } else {
                it
              }
            }
            _uiState.value = uiState.value.copy(devices = newDevices)
    }

关于android - _uiState.value = uiState.value.copy() 不会导致重组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73100123/

相关文章:

android - SetError 在 TextInputLayout 中使用自定义样式产生异常

安卓工作室 3.5 错误 : Unable to resolve dependency for ':app@debug/compileClasspath'

java - 如何模拟包含可能引发 NPE 的变量的类

angularjs - 可以从URL中获取参数

javascript - 以自定义方式显示和操作状态值

android - 获取字符串的 (Android.Graphics) 路径

java - Android Base64 音频文件编码/解码

android - 统一android : notifications and performance

kotlin - Kotlin-打印功能表达式

javascript - React - 在不使用 setState 的情况下更改状态 : Must avoid it?