到Github中搜redux-thunk,點(diǎn)開start最多的中間件的目錄,打開,有使用步驟,找到Installation先安裝
npm install redux-thunk
或
yarn add redux-thunk
在store的index中引入applyMiddleware方法狈孔,使我們可以使用中間件方法岭妖。
import { createStore , applyMiddleware} from 'redux';
再引入rudux模塊兒
import thunk from 'redux-thunk';
在createStore中添加applyMiddleware(thunk),
即創(chuàng)建store的時(shí)候會(huì)使用thunk中間件箕速。
以下是同時(shí)使用redux-devtools的代碼改寫
在 redux-devtools-extension
高級(jí)商店設(shè)置中
1.2 Advanced store setup
復(fù)制代碼
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(...middleware),
// other store enhancers if any
);
以便使用中間件thunk,同時(shí)引用redux_devtools
+ window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
代碼改寫如下
import { createStore , applyMiddleware,compose} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(thunk),
);
const store = createStore(
reducer,
enhancer,
);
export default store;
4.當(dāng)使用了redux_thunk以后,action可以是一個(gè)函數(shù)了
export const getTodoList = () => {
//使用了redux_thunk這里可以return一個(gè)函數(shù)了
return () => {
//函數(shù)里就可以做異步的操作
axios.get('/list.json').then((res)=>{
//此處使用Charles實(shí)現(xiàn)本地?cái)?shù)據(jù)帖世,(http://www.reibang.com/p/b73ca383a31b)
const data = res.data;
// console.log(data);
// const action = initListAction(data);
// dispatch(action);
}
}
5.調(diào)用getTodoList這個(gè)函數(shù)
到TodoList.js中引入getTodoList函數(shù)
import {getInputChangeAction,getAddItemAction,getDeleteItemAction,getTodoList} from './store/actionCreators'
創(chuàng)建一個(gè)action
const action = getTodoList();
//打印action,這里的action返回的是一個(gè)函數(shù)
componentDidMount() {
const action = getTodoList();
store.dispatch(action);//直接通過dispatch方法把a(bǔ)ction發(fā)給store沸枯,此時(shí)action里的函數(shù)會(huì)自動(dòng)執(zhí)行
console.log(action);
}
6.創(chuàng)建action改變store里的數(shù)據(jù)
export const initListAction = (data)=>({
type:INIT_LIST_ACTION,
data
});
export const getTodoList = () => {
return (dispatch) => {//getTodoList 是函數(shù)可以接收到store的dispatch方法日矫。
axios.get('/list.json').then((res)=>{
const data = res.data;
console.log(data);
const action = initListAction(data);
dispatch(action);//調(diào)用dispatch方法把a(bǔ)ction發(fā)給store
})
}
}
附加
什么是redux中間件
中間件是action和store之間的 ,對(duì)dispatch方法的封裝或升級(jí)