2.Redux学习2----redux-thunk

UI组件:只展示UI,不处理业务逻辑,又称傻瓜组件,因为只需要展示UI,没有状态,我们通常用函数组件(无状态组件)作为UI组件

容器父组件:只处理业务逻辑,不展示UI,又称聪明组件

redux-thunk中间件:中间件是指在action与store之间实现某种功能的插件,thunk插件可以让异步操作的代码写在aciton中,而不必写在组件生命周期里。
转至https://www.jianshu.com/p/1fb1299e4058

1.先安装redux-thunk依赖
npm install redux-thunk
yarn add redux-thunk redux-thunk的GitHub网址 : https://github.com/reduxjs/redux-thunk
 
 
2.接下来我们要引入配置redux-thunk这个中间件参考上面GitHub的网址上的文档
3.打开store文件夹下的index文件引入redux-thunk和配置redux开发者工具
import { createStore , applyMiddleware , compose } from "redux";
import reducer from "./reducer";
import thunk from 'redux-thunk';

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;
 
 
4.配置好后我们把组件里的异步代码移除,把异步代码移除到action中去
5.接下来我们打开actionCreators.js,当我们引用了Redux-thunk后action可以是一个函数
之前的action都是返回一个对象,现在可以用Redux-thunk返回一个函数
代码如下:
export const getTodoList = () => {
    return () => {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
            const data = res.data;
            })
        .catch(() =>{alert('err')})
    }
}
6.此时我们发现getTodoList这个函数该怎么调用呢
7.接下来我们就要返回到TodoList这个组件中去调用,首先引入这个方法
import { getInputChangeAction , getAddItemAction , getDeletItemAction ,getTodoList} from './store/actionCreators.js';
8.然后我们在componentDidMount这个生命周期函数中引用getTodoList这个函数 代码如下 :

    componentDidMount() {
    // 此时action是一个函数,这个函数中有请求数据的异步操作
     const action = getTodoList() // dispatch是派发action给store,若没有thunk中间件,action就必须是对象,发送函数会报错 // 有个thunk,作为一个中间件,判断是函数,就会先把action函数执行,而不是直接派发给store // 用thunk好像变复杂了,但目的是为了将异步请求放到aciton中处理,而不是生命周期中,因为一旦业务逻辑很多的时候,这么写非常简洁 // 放在action中也更便于自动化测试 store.dispatch(action)
 }
9.接下来我们返会到actionCreators.js中编写异步代码记得引入axios的包
import axios from 'axios';
10.那store中的List数据应该怎么改变呢,此时我们又要发送action啦代码如下:
const action = initListAction(data)
11.我们发现actionCreators并没有store的dispatch方法,当调用getTodoList时会生成一个内容似的函数时,这个函数能接收到stored的dispatch方法,我们直接调用dispatch法方就可以了 代码如下
export const getTodoList = () => {
    return (dispatch) => {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
            const data = res.data;
            const action = initListAction(data)
            dispatch(action);
            })
        .catch(() =>{alert('err')})
    }
}
 
 
 
 

原理:实际上thunk就是对dispatch方法做了封装,扩展了功能,使其可以进行异步操作

2.Redux学习2----redux-thunk_第1张图片

你可能感兴趣的:(2.Redux学习2----redux-thunk)