图片来网络 自己的理解 写给自己看
执行流程讲述:
1.View触发事件,一般情况下你可以直接在 Store
实例上(由connect函数提供)调用 dispatch()
(接受一个action
作为参数)。在 React native
中使用 Redux
,我们会使用 react-redux
提供的 connect
函数(从context对象中获取),它会提供一个 Store
实例内部的 dispatch
。 Store
就是把它们联系到一起的对象。Store
有以下属性和方法
- 提供
getState()
方法获取 state ; - 提供
dispatch(action)
方法更新 state ; - 通过
subscribe(listener)
注册监听器;用于订阅更新 - 通过
unsubscribe()
注销监听器。
- 更新时,假设有多个
reducer
的情况下,可以使用combineReducers
,当dispatch(action)
更新Store
时combineReducers
返回的rootreducer
会负责调用多个reducer
,然后会把多个结果集合并成一个state
3.Store
中的State
发生变化,通过subscribe(listener)
注册监听器; 订检测到更新,调用setState
更新包装组件(connect函数会返回一个新的组件),再将组件`State 传递给真实组件,完成更新。
文中有关的知识:
react-redux
提供的 Provider
包裹Store
传递到子组件。
###上述是redux同步应用
下面介绍异步redux
异步redux需要分析一下源码才能够说清楚。
异步redux需要redux-thunk,之后再说怎么自己实现异步redux。
redux-thunk提供了thunk,react-redux提供了applyMiddleware
下面看 applyMiddleware源码
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, preloadedState, enhancer) => {
const store = createStore(reducer, preloadedState, enhancer)
let dispatch = store.dispatch
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
applyMiddleware 返回一个函数,参数是createStore,这个函数也返回了一个函数,参数为reducer, preloadedState, enhancer。刚好对应 applyMiddleware(thunk)(createStore)(reducers);thunk为第一个参数,createStore为第二个参数,reducers为第三个参数。最后返回Store和dispatch,这个dispatch经过改造,可以接受参数为函数的方法,具体实现在redux-thunk源码里面如下:
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
其中thunk作为参数传递给...middlewares,此时数组里只有一个元素。
chain = middlewares.map(middleware => middleware(middlewareAPI))
这里面返回
next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
dispatch = compose(...chain)(store.dispatch)
它返回
action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action)
};
拿fetch做例子,你可以在fetch的时候dispatch一个action type为loading,
在成功的时候dispatch一个action type为sucess
在失败的时候dispatch一个action type为fail
而不需要自己去拓展一些功能