Redux之使用redux-thunk进行ajax请求发送

 

1:中间件流程图

 

2:Redux-thunk作用:

简单说:当组件中有复杂的异步请求时,为了减少组件的复杂程度

把异步请求使用此中间件放在actionCreator.js中

3:使用之前

使用之前是在组件内进行数据请求

store/index.js

//store.js

import {createStore,applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';

//1-store是唯一的
//2-只有store才能改变自己的内容(state)
//3-reducer必须是纯函数
const store = createStore(
    reducer,
);
export default store;

TodoList.js 

//TododList.js
//视图渲染之后使用axios进行ajax请求,进行初始化
componentDidMount(){
   axios.get('https://api.github.com/users')//上面已经引入地址
       .then((res)=>{
          // console.log(res);//得要所有结果
           const data=res.data;//具体看数据
         //  console.log(data)
           const action=initListAction(data);
           store.dispatch(action);
       })

}

store/actionCreator.js 

//actionCreator.js
export const initListAction=(data)=>({
    type:INIT_LIST_ACTION,
    data,
});

4:使用

使用之后是在actionCreator.js中进行网络请求

4.1:安装:

npm install --save redux-thunk

4.2:使用:在store/index.js中引用(已经安装了react官方脚手架)

store/index.js 

import {createStore,applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';

//1-store是唯一的
//2-只有store才能改变自己的内容(state)
//3-reducer必须是纯函数
const store = createStore(
    reducer,
    applyMiddleware(thunk),//这个方法表示:使用thunk这个中间件
);
export default store;

TodoList.js 

   //TododList.js
    //视图渲染之后使用axios进行ajax请求,进行初始化
    componentDidMount() {
        const action = getTodoList();//此时action返回的不再是一个对象,而是一个函数,
        store.dispatch(action);//此时action是个函数,这个函数执行完了之后,才最后转发给store,store自动转发给reducer
    }

store/actionCreator.js  


//actionCreator.js
export const initListAction=(data)=>({
    type:INIT_LIST_ACTION,
    data,
});

//使用redux-thunk中间件之后允许返回一个函数
export const getTodoList=()=>{
    return (dispatch)=>{
        axios.get('https://api.github.com/users')//上面已经引入地址
            .then((res)=>{
                const data=res.data;
                const action=initListAction(data);
                dispatch(action);//转发给调用此方法的常量
            })

    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值