简体   繁体   English

在jetpack compose中使用非本地state?

[英]Use non-local state in jetpack compose?

Is it Ok to use non-local state from a Composable function?可以从可组合 function 中使用非本地 state 吗? An example would be a Composable that shows a Text with a String taken from a MutableState stored as a member of an object retrieved through an Ambient, like this:一个示例是 Composable,它显示带有从MutableState获取的字符串的 Text,该字符串存储为通过 Ambient 检索的 object 的成员,如下所示:


data class ServiceX (
   val whateverString: MutableState<String>("meow")
)


@Composable
fun Whatever() {
   val serviceX = AmbientServiceX.current
   Text(serviceX.whateverString)
}

Will the Composable function repaint when whateverString changes?whateverString发生变化时,可组合function会重新绘制吗? Are there any problems with this?这有什么问题吗?

It should technically work, But you'd probably want to change MutableState to mutableStateOf which does some more compose goodies under the hood.从技术上讲,它应该可以工作,但是您可能希望将MutableState更改为mutableStateOf ,这会在幕后制作更多的好东西。

But I'd suggest avoiding patterns like this in compose.但我建议在 compose 中避免使用这样的模式。 Ambients in general should be used rarely, as ambients make composables 'magic' with it being non obvious where the value came from or where a value change was triggered.一般来说,环境应该很少使用,因为环境使可组合物变得“神奇”,它不明显值来自何处或触发值更改的位置。 It essentially makes your code very hard to debug.它本质上使您的代码很难调试。

Lean on the side of creating isolated components as these are way simpler to build and maintain - and are the big benefit of compose.倾向于创建孤立的组件,因为这些组件更易于构建和维护 - 并且是 compose 的一大好处。

@Composable
fun Whatever(whateverString: String) {
   Text(whateverString)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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