redux三个基础的API:
- Action:redux中的state需要通过action去更新,store.dispatch(action)去分发actions,每个action需要有一个命名和return
- Reducer:actions只是描述有state更新,需要reducer去描述应该如何更新state,可以处理多个action。redux还提供combineReducers({})处理多个reducer,作为参数传给createStore()。
- Middleware:作为action和reducer之间的中间状态(action -> middlewares -> reducer),提供applyMiddleware()创建中间件,作为参数传给createStore()。异步触发action的中间件react-thunk,原来的store.dispatch()方法只能接受一个普通的actions对象作为参数,加入react-thunk中间件后还可以接收一个方法作为参数,这个方法接收两个参数,分别是dispatch和getState,分别对应store.dispatch()和store.getState()。例如:
store.dispatch((dispatch, getState) => dispatch({type: 'INCREASE'})); - Store:负责联系Action和Reducer,有以下职责:
- 维持应用的state
- 提供getState()方法获取state
- 提供dispatch(action)更新state
- 通过subscribe(listener)注册监听器
- 通过subscribe(listener)返回的函数注销监听器
- 提供createStore(reducers)封装combineReducer(reducers)后的多个reducers,保证store只有一个,便于维护state,而Reducer可以多个。
react-redux:(把redux和react连接起来)
- 提供<Provider store={store}>组件封装store,保证可以通过props取到store里面管理的state
- 提供connect(mapStateToProps, mapDispatchToProps, [mergeProps], [options])封装redux里面的state给props