中间件原理:
中间件?是谁的中间件?谁和谁的中间?
是action和store中间,action和store中间是通过dispatch方法连接的,所以,redux-thunk中间件,实际上是对dispatch方法做的封装改造!!!
redux-logger
redux-thunk 异步逻辑放到action中处理
redux-saga 异步逻辑单独处理
1.redux-thunk是redux的中间件,是用来丰富redux的功能的,不是react的中间件
好处:
正常情况下,redux中的actionCreators创建的action值能是对象,但是,使用了redux-thunk后,action的返回值可以函数!!!可以写异步代码
- 下载插件 npm install redux-thunk
- 使用:创建store时使用
import {createStore,applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
// 1.先引入applyMiddleware
// 2. 通过redux创建store时使用中间件,中间件是redux的,不是react的
// 同时使用redux-thunk和__REDUX_DEVTOOLS_EXTENSION_COMPOSE__这两个中间件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk));
const store = createStore(
reducer, // 构建初始数据
// chrome调试redux
enhancer
);
这样编写的action可以长这样:
// 使用redux-thunk后 ,action返回的东西可以是函数
export const getTodoList = ()=>{
return (dispatch)=>{
axios.get('/list.json').then((res)=>{
const data =res.data;
dispatch('xx-action');
}).catch()
}
}
当store.dispatch(action),若action是一个function,store会自动调用这个方法