您的位置:首页 > 其它

redux-thunk使用

2020-01-15 07:30 169 查看

引入中间件解决纯函数不能使用异步,其它函数的代码

*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()()
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
Zhencode 发布了46 篇原创文章 · 获赞 1 · 访问量 997 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: