react入门系列之使用redux-thunk中间件发起异步请求

### redux-thunk

- redux-thunk是redux中的一个中间件
- 安装命令 yarn add redux-thunk
- 在store文件夹中的index.js中引入applyMiddleware,这样我们才能使用中间件
- 然后再引入redux-thunk
- 并在createStore中使用applyMiddleware(thunk)

#### 到底生命是redux中间件

- 谁和谁之间
- action和store之间
- 其实中间件就是对dispath一个封装
- 如果传递的是一个函数,会让这个函数先执行再传递给store
- 如果是一个对象,就直接传递给store
- 所以使用thunk中间件以后action可以是一个函数
 1 /**
 2 * store就像一个图书管理员,在接到组件(借书人)派发的 dispatch(借书人说的话) 时,
 3 * 他本身不知道书在什么位置,有没有这本书,需要查询 reducer (图书列表)
 4 */
 5 import { createStore, applyMiddleware, compose } from 'redux'
 6 import thunk from 'redux-thunk'
 7 import todoListReducer from './reducer' // 引入图书列表
 8 
 9 
10 // 使用redux-devtools中间件和redux-thunk中间件
11 
12 
13 const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
14 const enhancer = composeEnhancers(
15 applyMiddleware(thunk)
16 )
17 const store = createStore(
18 todoListReducer,
19 enhancer
20 ) // 查询图书列表
21 
22 
23 export default store

 

### 使用redux-thunk

- 在项目中使用引入使用redux-thunk之后
- 在actionCreators中创建action不再只能创建对象action了,能够创建函数形式的action
- 因为action能是个函数,所以我们可以把异步请求放在action中而不是放在生命周期函数里面
- 项目大的时候逻辑复杂的时候,异步请求放在钩子函数里是不好的
 1 import { CHANGE_INPUT_VALUE, CHANGE_LIST_VALUE, DELETE_LIST_VALUE, INIT_DATA } from './actionTypes'
 2 import mockData from '../mockjs/mock';
 3 import axios from 'axios'
 4 
 5 
 6 export const getInputChangeValue = (value) => ({
 7 type: CHANGE_INPUT_VALUE,
 8 value
 9 })
10 
11 
12 export const getAddTodoListValue = (item) => ({
13 type: CHANGE_LIST_VALUE,
14 item
15 })
16 
17 
18 export const getDeletTodoListValue = (index) => ({
19 type: DELETE_LIST_VALUE,
20 index
21 })
22 
23 
24 export const initData = (data) => ({
25 type: INIT_DATA,
26 data
27 })
28 /**
29 * 因为使用了redux-thunk所以在actionCreators中的箭头函数可以返回一个函数
30 */
31 export const getToduList = () => {
32 return (dispatch) => { // 这个action返回的是这样一个箭头函数,在使用的时候同样页需要通过dispatch派发,箭头函数中dispath其实就是在派发这个action的时候传递进来的
33 axios.get('http://getTodoList', {dataType: 'json'}).then(res => {
34 const action = initData(res.data.data)
35 dispatch(action)
36 })
37 }
38 }

 

### 在组件中使用这个异步请求
 
- 在componentDidMount函数中使用了
  1 /**
  2 * 组件就是一个需要借书的人,通过 dispatch 传达 action (书名)给图书管理员(store)
  3 */
  4 
  5 import React, { Component }from 'react';
  6 import { message } from "antd";
  7 import store from './store'; // 引入图书管理员 store
  8 import AppUi from './AppUi';
  9 // import mockData from './mockjs/mock';
 10 // import axios from 'axios'
 11 // 引入action
 12 import { getInputChangeValue, getAddTodoListValue, getDeletTodoListValue, getToduList } from './store/actionCreators'
 13 // import { CHANGE_INPUT_VALUE, CHANGE_LIST_VALUE, DELETE_LIST_VALUE } from './store/actionTypes'
 14 import "antd/dist/antd.css";
 15 class App extends Component {
 16 constructor(props){
 17 super(props)
 18 this.state = store.getState()
 19 console.log(store.getState())
 20 this.handleInputChange = this.handleInputChange.bind(this);
 21 this.addTodoList = this.addTodoList.bind(this);
 22 this.handleStroeChange = this.handleStroeChange.bind(this);
 23 this.deletTodoList = this.deletTodoList.bind(this);
 24 store.subscribe(this.handleStroeChange) // 图书管理员会随时通知各个借书人,图书馆书籍的变化
 25 }
 26 componentDidMount (){
 27 // 引入了actionCreators中的getToduList方法,他返回的是一个函数action
 28 const action = getToduList()
 29 // 所以这里使用dispact去派发这个action
 30 store.dispatch(action)
 31 /*
 32 axios.get('http://getTodoList', {dataType: 'json'}).then(res => {
 33 console.log(res.data.data)
 34 this.init(res.data.data)
 35 console.log(this.state)
 36 })
 37 */
 38 }
 39 render() {
 40 return (
 41 <AppUi
 42 inputValue = {this.state.inputValue}
 43 handleInputChange = {this.handleInputChange}
 44 deletTodoList = {this.deletTodoList}
 45 addTodoList = {this.addTodoList}
 46 list = {this.state.list}
 47 />
 48 )
 49 }
 50 handleInputChange(e) {
 51 /*
 52 const action = {
 53 type: CHANGE_INPUT_VALUE, // 借什么书
 54 value: e.target.value
 55 }
 56 */
 57 const action = getInputChangeValue(e.target.value)
 58 store.dispatch(action); // 传达给store
 59 console.log(e.target.value)
 60 }
 61 /*
 62 // 数据初始化
 63 init(data) {
 64 const action = initData(data)
 65 store.dispatch(action)
 66 }
 67 */
 68 // 添加
 69 addTodoList() {
 70 /*
 71 if (this.state.inputValue) {
 72 const action = {
 73 type: CHANGE_LIST_VALUE,
 74 item: this.state.inputValue
 75 }
 76 store.dispatch(action)
 77 } else {
 78 message.warning('请输入内容');
 79 }
 80 */
 81 if (this.state.inputValue) {
 82 const action = getAddTodoListValue(this.state.inputValue)
 83 store.dispatch(action)
 84 } else {
 85 message.warning('请输入内容');
 86 }
 87 }
 88 // 删除
 89 deletTodoList(index) {
 90 /*
 91 const action = {
 92 type: DELETE_LIST_VALUE,
 93 value: index
 94 }
 95 */
 96 console.log(index)
 97 const action = getDeletTodoListValue(index)
 98 store.dispatch(action)
 99 }
100 handleStroeChange() {
101 this.setState(store.getState()) // 每当图书馆有变化的时候,图书管理员(store)通过这个方式告诉借书人(组件)
102 }
103 }
104 export default App;

 

 

转载于:https://www.cnblogs.com/boye-1990/p/11468473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值