Redux 之 Middleware 及 Flutter Redux 介绍


一、前言

在前一篇博客,我们介绍了 Redux 的基本概念,本次对内容进行提升。
传送门: https://jxr202.github.io/2022/10/27/redux/redux_001

二、概念介绍

对象 说明
Store Redux 数据集合、仓库,内部包含了 Reducer、State、Middleware
Action Redux 一种用于触发 State 变化的动作或行为
Reducer Redux 纯函数,约束 State 的变化,根据 Action 得出新的 State
State Redux UI 状态,不同的 State 意味着不同的 UI
Middleware Redux 中间件,类似于拦截器,在 Action 到 Reducer 之前进行拦截
StoreProvider Flutter_Redux 继承于 InheritedWidget,用于 Store 的注入
StoreConnector Flutter_Redux 用于关联 Store 和 Widget,实现自动刷新

三、StoreProvider

  • StoreProvider 通常用于 Store 的注入,即 App 的入口的地方。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    void main() {
    final store = Store<AppState>(counterReducer, initialState: const AppState.initState());
    runApp(MyApp(store));
    }

    /// MyApp -> build()
    @override
    Widget build(BuildContext context) {
    return StoreProvider<AppState>(
    store: store,
    child: MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
    primarySwatch: Colors.blue,
    ),
    home: const HomePage(title: 'Flutter Demo Home Page'),
    ),
    );
    }

四、StoreConnector

  • StoreConnector 用于接收 Store 中的 State 变化,然后局部刷新 UI。

  • 尽量缩小 StoreConnector 的范围,优化 UI 的绘制流程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    body: Center(
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
    const Text('You have pushed the button this many times:'),
    StoreConnector<AppState, int>(
    converter: (store) => store.state.count,
    builder: (context, count) {
    return Text(
    '$count',
    style: Theme.of(context).textTheme.displayLarge,
    );
    },
    ),
    ],
    ),
    ),


Redux 之 Middleware 及 Flutter Redux 介绍
http://jxr202.github.io/redux/redux_002-2aaea8fc239a/
作者
Jiang
发布于
2022年11月3日
许可协议