作用:解決異步代碼的問題
[文檔地址](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);
}
~~~
- react
- 第一章 React入門
- 1-1 開發環境搭建
- 1-2 循環
- 1-3 jsx語法
- 1-4 react特點
- 第二章 基本語法
- 2-1 組件
- 2-2 實現一個簡單的TodoList
- 2-2-1刪除
- 2-3 組件之間的傳值
- 2-4 子組件向父組件傳值
- 2-5 react-router實現一個簡單路由
- 2-6 ref的使用
- 2-7 setState方法
- 2-8 生命周期函數
- 2-9 react的css過渡動畫
- 2-10 react中的內聯樣式
- 2-11 事件
- 2-12 箭頭函數
- 第三章 redux
- 第一節 使用
- 1.1 action
- 1.2 實現todoList的增刪功能
- 1.3 actionTypes的拆分
- 1.4 actionCreators.js統一管理action
- 1-5 redux設計的三大原則
- 第二節 安裝Redux
- 第三節 redux進階
- 3.1 ui組件和容器組件的拆分
- 3.2無狀態組件
- 3.3 Redux-thunk中間件ajax請求數據
- 3.4redux中間件
- 3.5 redux-saga中間件
- 第四節 react-redux
- 第四章 項目啟動
- 第一節 styled-components
- 1-1 style 引入背景圖片
- 1-2 樣式組件
- ant-design
- 1.起步