引入中间件解决纯函数不能使用异步,其它函数的代码
*store.js*
import {applyMiddleware,createStore,compose} from 'redux'
import reducers from './reducers.js'
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(reducers,enhancer)
export default store
*actions.js*
import store//引入store
export const getListAction=(data)=>({type:GET_TODO_LIST,data:data})
export const getList=()=>{
return ()=>{
// thunk中间件,getListAction在getList间接使用并分发reducers,axios为非纯函数代码
axios.get('https://douban.uieee.com/v2/book/search?q=虚构类&count=8').then(res=>{
const data=res.data.books
const action=getListAction(data)
store.dispatch(action)
}).catch(err=>{
console.log(err)
})
}
}
*reducers.js*
switch (action.type) {
case GET_TODO_LIST:
newState.data=action.data
return newState
default:
break;
}
*app组件*
import getList from './actions'
//getToDoList为在组件中componentWillMount自定义的函数
getToDoList=()=>{
getList()()
}