合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
作用:解决异步代码的问题 [文档地址](https://github.com/reduxjs/redux-thunk#installation) ## 1.安装 ~~~ npm install redux-thunk ~~~ ~~~ import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers/index'; // Note: this API requires redux@>=3.1.0 const store = createStore( rootReducer, applyMiddleware(thunk) ); ~~~ ## 2.精确配置 [地址](https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup) ~~~ 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) ); const store = createStore( reducer, enhancer ); export default store; ~~~ ## 3.将http请求放在actionCreator.js中 ~~~ import {change_input_value,add_todo_item,delete_item,http} from './actionTypes'; import axios from 'axios-jsonp-pro'; const getInputChangeAction =(value)=>{ return { type:change_input_value, value } } const getAddItemAction =()=>{ return { type:add_todo_item } } const getDeleteItemAction=(index)=>{ return { type:delete_item, index } } const getHttpData=(data)=>{ return { type:http, data } } const getTodoList=()=>{ return (dispatch)=>{ var url = "https://api.douban.com/v2/movie/top250" axios.jsonp(url).then(res=>{ var subjects = res.subjects; var titles = [] subjects.forEach(ele=>{ var title = ele.title titles.push(title) }) let action = getHttpData(titles); dispatch(action) }) } } export {getInputChangeAction,getAddItemAction,getDeleteItemAction,getHttpData,getTodoList}; ~~~ ## 4.在组件componentDidMount中调用 ~~~ componentDidMount(){ const action = getTodoList(); store.dispatch(action); } ~~~