Advertisement

Redux thunk | 什么是thunk?在React项目中怎么使用Redux-Thunk?

阅读量:

Redux-thunk

什么是thunk?

thunk可以理解为函数的另一种称呼,但不是以前我们说的简单函数。Thunk代表的是一个被其他函数返回的函数。

复制代码
    function wrapper_function() {
      // this one is a "thunk" because it defers work for later:
      return function thunk() {   // it can be named, or anonymous
        console.log('do stuff now');
      };
    }
    
    
      
      
      
      
      
      
    
    AI写代码

如果你已经理解了这个模式,可以不叫它thunk,叫它wrapper_function()()。

那么它是怎么作用在redux上的呢?

Redux中有几个概念:”actions”,”action creators”,”reducer”,“middleware”
不熟悉Redux的话,可以看一下Redux官方文档

Actions就是普通对象,并且一定有一个type属性,除了这个,你可以在对象中自定义你想要描述该action的数据。

复制代码
    // 1. plain object
    // 2. has a type
    // 3. whatever else you want
    {
      type: "USER_LOGGED_IN",
      username: "dave"
    }
    
    
      
      
      
      
      
      
      
    
    AI写代码

每次都要手写action对象会很麻烦,redux有一个“action creators ”的概念来简化。

复制代码
    function userLoggedIn() {
      return {
    type: 'USER_LOGGED_IN',
    username: 'dave'
      };
    }
    
    
      
      
      
      
      
      
    
    AI写代码

你可以通过调用userLoggedIn函数来生成这个action,如果你在app中多次dispatch同样的action,使用action creators会大大简化工作。

Action可以做点什么吗?

Action虽然叫action,但其实什么都不做,只是对象而已。它们可以自己做点什么吗?比如像调用api或是触发其他actions?
因为reducer必须是纯函数,我们不能在reducer里调用api或是触发其他actions。

如果我们希望action做些什么,就要把代码放进一个函数中去,这个函数就是thunk。

Action creators返回一个函数而不是一个action对象。

复制代码
    function getUser() {
      return function() {
    return axios.get('/current_user');
      };
    }
    
    
      
      
      
      
      
    
    AI写代码

那么怎么让Redux处理actions是函数的情况呢?

我们就引入了redux-thunk,它是一个中间件,每次action都会经历它,如果action是一个函数,就调用这个函数,这就是redux-thunk做的事。

传递给thunk函数的就是两个参数:

  1. Dispatch,如果它们需要,可以dispatch新的action。
  2. getState,它们可以获取最新的state。
复制代码
    function logOutUser() {
      return function(dispatch, getState) {
    return axios.post('/logout').then(function() {
      // pretend we declared an action creator
      // called 'userLoggedOut', and now we can dispatch it
      dispatch(userLoggedOut());
    });
      };
    }
    
    
      
      
      
      
      
      
      
      
      
    
    AI写代码

Redux-thunk库

Redux-thunk库真的很小,所有的代码如下:

复制代码
    function createThunkMiddleware(extraArgument) {
      return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    
    return next(action);
      };
    }
    
    const thunk = createThunkMiddleware();
    thunk.withExtraArgument = createThunkMiddleware;
    
    export default thunk;
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

你安装完redux-thunk后,引用它,每次dispatch的action都会经过以上这些代码。如果action是函数的话就调用它们,否则就传递action给下一个中间件,或是redux本身。

安装redux-thunk

  1. 安装redux-thunk包
    npm install --save redux-thunk

  2. 导入redux-thunk并插入redux

复制代码
    // You probably already import createStore from 'redux'
    // You'll need to also import applyMiddleware
    import { createStore, applyMiddleware } from 'redux';
    
    // Import the `thunk` middleware
    import thunk from 'redux-thunk';
    
    // Import your existing root reducer here.
    // Change this path to fit your setup!
    import rootReducer from './reducers/index';
    
    // The last argument to createStore is the "store enhancer".
    // Here we use applyMiddleware to create that based on
    // the thunk middleware.
    const store = createStore(
      rootReducer,
      applyMiddleware(thunk)
    );
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

参考资料:
redux-thunk github
What the heck is a ‘thunk’?

全部评论 (0)

还没有任何评论哟~