文件结构

- AppState: 用来声明项目State结构
- RootReducer: 项目的根reducer,用来处理action,是一个纯方法
- ChildReducer (VideoReducer): 用来声明state里的具体状态以及reducer,可以具有很多文件来组成整个项目的状态
- createStore: 用来创建Redux Store,app通过Store对象来控制app的状态
ChildReducer (VideoReducer)
import Foundation
import Redux
struct Video: Codable {
var name: String
var url: String
}
//
struct VideoState: Codable, Persistent {
var fetching: Bool = false
var data: [Video] = []
init() {}
init(persistedState: VideoState) {
self = persistedState
}
func persist() -> VideoState {
self
}
}
// Action
struct VideoRequestAction: Action {
}
struct VideoRequestSuceessAction: Action {
let data: [Video]
}
// reducer
func videoReducer(_ state: VideoState?, _ action: Action) -> VideoState {
let state = state ?? VideoState()
if let action = action as? VideoRequestAction {
return request(state: state, action: action)
}else if let action = action as? VideoRequestSuceessAction {
return requestSuccess(state: state, action: action)
}
return state
}
let persistentVideoReducer = persistReducer(reducer: videoReducer)
// reducer func
fileprivate func request(state: VideoState, action: VideoRequestAction) -> VideoState {
var state = state
state.fetching = true
return state
}
fileprivate func requestSuccess(state: VideoState, action: VideoRequestSuceessAction) -> VideoState {
var state = state
state.fetching = false
state.data = action.data
return state
}