ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
作用:解决异步代码的问题 [文档地址](https://github.com/reduxjs/redux-thunk#installation) ## 1.安装 ~~~ npm install redux-thunk ~~~ ~~~ //store>index.js 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中 ~~~ // 直接将action进行封装使用 import {inputChange,addItem,deleteItem,http} from "./actionType.js"; import axios from "axios-jsonp-pro" const valueChangeAction=(value)=>{ return { type:inputChange, value } } const valueaddItemAction=(value)=>{ return { type:addItem, value } } const valuedeleteItemAction=(index)=>{ return { type:deleteItem, index } } const httpAction=(value)=>{ return{ type:http, value } } //中转(定义一个方法将action对象装在函数中,通过redux-htunk传递的是这个封装的函数而不是action,相当于是对ajax的一个封装在其他页面、组件中直接调用即可) const getHttpTitlesAction=()=>{ return (dispatch)=>{ var url="https://douban.uieee.com/v2/movie/top250"; axios.jsonp(url).then(res=>{ console.log(res); var subjects=res.subjects; var titles=[]; subjects.forEach(element => { var{title}=element titles.push(title) }); //调用上面封装的action dispatch(httpAction(titles)); }) } } export{valueChangeAction,valueaddItemAction,valuedeleteItemAction,httpAction,getHttpTitlesAction} ~~~ ## 4.在组件componentDidMount中调用 ~~~ //app.js import {valueChangeAction,valueaddItemAction,valuedeleteItemAction,httpAction,getHttpTitlesAction} from "../store/actionCreators" componentDidMount(){ store.dispatch(getHttpTitlesAction()); } ~~~