Redux-thunk教程


什么时候需要redux-thunk中间件

在未引入redux-thunk,store.dispatch(action)的action只能是对象,dispatch只是把action传给reducer。
引入redux-thunk后,store.dispatch(action)的action可以是函数,在action里可以调接口获取数据,再传给store。

准备工作

npm install –save redux-thunk

入口文件: store/index.js
1
2
3
4
5
6
7
8
9
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import reducer from './page/reducer' // 引入reducer模块

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose // compose的引入是未了使用redux dev tools插件
const enhancer = composeEnhancers(applyMiddleware(thunk))
const store = createStore( reducer, enhancer) // 创建数据存储仓库
export default store
模块书写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// store/page/reducer.js
import * as type from './action-type'
const defaultState = {
inputValue: 'value',
list: [
'早上4点起床,锻炼身体',
'中午下班游泳一小时'
]
} //储存数据
export default (state = defaultState, action) => {
let newState = JSON.parse(JSON.stringify(state))
if (action.type === type.CHANGE_INPUT) {
newState.inputValue = action.value
return newState
}
if (action.type === type.CHANGE_LIST) {
newState.list = action.value
return newState
}
console.log(state, action)
return state
}

// store/page/action-type.js
export const CHANGE_INPUT = 'changeInput'
export const CHANGE_LIST = 'changeList'
export const DELETE_ITEM = 'deleteItem'

// store/page/action.js
import * as type from './action-type'
import axios from 'axios'
import store from '../index'

export const changeInputAction = (value) => ({
type: type.CHANGE_INPUT,
value
})

export const changeListAction = (value) => ({
type: type.CHANGE_LIST,
value
})

export const getTodoList = () => {
return () => {
axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res)=>{
const action = changeListAction(res.data.data.list)
store.dispatch(action)
})
}
}

// 组件
componentDidMount () {
const action = Action.getTodoList()
store.dispatch(action) // 执行axios函数
}