Flutter 开发实战

235课时
1K学过
8分

课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
2分钟

02 Redux-2

根据这个流程,首先我们要创建一个 Store 。如下图,创建 Store 需要 reducer ,而 reducer 实际上是一个带有 stateaction 的方法,并返回新的 State 。

img

所以我们需要先创建一个 State 对象 GSYState 类,用于储存需要共享的数据。比如下方代码的: 用户信息、主题、语言环境 等。

接着我们需要定义 Reducer 方法 appReducer:将 GSYState内的每一个参数,和对应的 action 绑定起来,返回完整的 GSYState这样我们就确定了 State 和 Reducer 用于创建 Store

///全局Redux store 的对象,保存State数据
class GSYState {
  ///用户信息
  User userInfo;
  
  ///主题
  ThemeData themeData;

  ///语言
  Locale locale;

  ///构造方法
  GSYState({this.userInfo, this.themeData, this.locale});
}

///创建 Reducer
///源码中 Reducer 是一个方法 typedef State Reducer<State>(State state, dynamic action);
///我们自定义了 appReducer 用于创建 store
GSYState appReducer(GSYState state, action) {
  return GSYState(
    ///通过自定义 UserReducer 将 GSYState 内的 userInfo 和 action 关联在一起
    userInfo: UserReducer(state.userInfo, action),
    
    ///通过自定义 ThemeDataReducer 将 GSYState 内的 themeData 和 action 关联在一起
    themeData: ThemeDataReducer(state.themeData, action),
    
    ///通过自定义 LocaleReducer 将 GSYState 内的 locale 和 action 关联在一起
    locale: LocaleReducer(state.locale, action),
  );
}

如上代码,GSYState 的每一个参数,是通过独立的自定义 Reducer 返回的。比如 themeData是通过 ThemeDataReducer方法产生的,ThemeDataReducer其实是将 ThemeData和一系列 Theme 相关的 Action 绑定起来,用于和其他参数分开。这样就可以独立的维护和管理 GSYState 中的每一个参数。