React 之 redux-thunk

作者 糖一瓶 日期 2018-04-01
React 之 redux-thunk
    首先是了解一下目录结构:
    test
     |-node_modules
     |-www     
         |-app    
           |-main.js
           |-App.js
           |-reducers
               |-index.js
               |-counterReducer.js
           |-actions
                  |-counter.js
         |-index.html
     |-webpack.config.js
     |-package.json

一、什么是redux-thunk?

  • 首先来了解一下它的用处:
    我们想实现如图功能,点击按钮家接口那么多。
    1
    思路是:点击按钮之后,发出ajax请求,将请求回来的数据当做载荷改变reducer。
    我们在使用redux的时候,如果想调用异步请求来的接口数据,用redux的想法,大家应该会这么写:
    actions/counter.js:
    export const add = () => ({ "type": "ADD"});
    export const minus = () => ({ "type": "MINUS"});
    export const cheng = () => ({ "type": "CHENG"});
    // 这里异步调用
    export const addServer = () => {
      $.get("/api/api" , function(data){
          return {"type" : "ADDSERVER" , "v" : data.v}
      })   
    };
    

但是这是错误的!!!因为你的return是返回内层的函数,并不是外层的函数!!!

所以就有个人开发出了一个叫做redux-thunk的东西来解决异步调用数据的问题。

二、具体使用

安装redux-thunk

npm install –save redux-thunk

配置极其简单,就是一个插件,所以要加入applyMiddleware:
改变项目的入口文件main.js:

import React from "react";
import ReactDOM from "react-dom";
// 加入applyMiddleware
import {createStore , applyMiddleware} from "redux";
import {Provider} from "react-redux";
// 引入redux-thunk
import thunk from "redux-thunk";

import App from "./App.js";
import reducer from "./reducers";

// 配置插件
const store = createStore(reducer, applyMiddleware(thunk));

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    ,
    document.getElementById("app")
);

就完成了thunk的配置。

我们来到actions/counter.js文件,此时所有的异步函数都依法可以写两个()=>()=>{}

export const add = () => ({ "type": "ADD"});
export const minus = () => ({ "type": "MINUS"});
export const cheng = () => ({ "type": "CHENG"});
// 异步的写法
export const addServer = () => (dispatch , getState) => {
    $.get("/api/api" , function(data){
        dispatch({"type" : "ADD" , "v" : data.v})
    });
}
  • 第二个()有dispatch与getState参数

redux-thunk不仅仅能够解决异步问题,而且还能解决副作用问题。副作用:异步或者if语句体。

export const add = () => ({ "type": "ADD"});
export const minus = () => ({ "type": "MINUS"});
export const cheng = () => ({ "type": "CHENG"});

export const addServer = () => (dispatch , getState) => {
    $.get("/api/api" , function(data){
        dispatch({"type" : "ADD" , "v" : data.v})
    });
}

export const addOdd = () => (dispatch , getState) => {
    //getState表示得到当前的state
    if(getState().counter.v % 2 == 0){
        dispatch({ "type": "ADD" })
    }
}

总结一下

redux-thunk就是redux的一个插件。帮助redux解决异步和副作用问题。