中间件指的是什么呢,就是对dispatch方法的一个封装
中间件就是一个函数,对store.dispatch方法进行了改造,在发出 Action 和执行 Reducer 这两步之间,添加了其他功能
安装
npm install --save redux-thunk
在stroe/index.js中配置
配置之前 用的 redux_devtools
import {createStore} from 'redux'
import reducer from './reducer'
//createStore生成store 接受另外一个函数 返回一个新的store对象
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(reducer,composeEnhancers );
export default store
配之后
import {createStore,applyMiddleware, compose} from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk))
//createStore生成store 接受另外一个函数 返回一个新的store对象
// const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
const store = createStore(reducer,enhancer )
export default store
修改 todolist.js中的异步方法axios
在action.js中改造
const getList=(data)=>({
type:GET_LIST,
value:data
})
//中间件
const gettodolist =()=>{
return (dispatch)=>{ //返回一个函数
Axios.get('json/list.json').then((res)=>{
const data = res.data.data.list
console.log('ccc'+data)
dispatch( getList(data) ) //出入store
})
}
}
componentDidMount(){
// Axios.get('json/list.json').then((res)=>{
// const data = res.data.data.list
// console.log('ccc'+data)
// store.dispatch( getList(data) ) //出入store
// })
//使用thunk中间件 把 action和dispatch进行了改造
store.dispatch(gettodolist())
}
redux的中间件指的是action和store之间。之前我们说action只能是一个对象,所以action是一个对象直接派发给了store。但是现在,当我们使用了redux-thunk之后,action可以是函数了