Compose 提升状态的场景

114 阅读1分钟

Where to hoist that state in Compose?

了解在 Jetpack Compose 中提升状态的方式和场景。

1. Composable functions

例子:点击 Message 展示消息时间。

image.png

image.png

这个 UI 逻辑,不需要提升状态,showDetails 状态只在 ChatBubble 中管理。

Not hoisting is a valid option.

不提升状态是一个合理的选择。

2. State hoisting

在下面的例子中,消息列表的状态需要提升。

image.png

image.png

image.png

image.png

image.png

image.png

Place state in the lowest common ancestor.

将状态置于最低公共祖先。

3. Plain state holder class

使用 state holder class 做状态提升,例如 LazyListState。

image.png

LazyListState 抽象了 scrollPosition 同时暴露了应用逻辑的方法,比如 scrollToItem()、scroll()、animateScrollToItem()。

4. Android architecture Components(AAC)ViewModel

使用 ViewModel 做状态提升。

image.png

image.png

image.png

5. Recap

image.png

image.png

Keep state as low as possible.

尽可能把状态所在层级放低,不要过多暴露出去。