代码之家  ›  专栏  ›  技术社区  ›  James Lin

带链式箭头函数的redux mapDispatchToProps

  •  1
  • James Lin  · 技术社区  · 6 年前

    const mapStateToProps = state => {
      return {
        todo: state.todos[0]
      }
    }
    
    const mapDispatchToProps = dispatch => {
      return {
        destroyTodo: () =>
          dispatch({
            type: 'DESTROY_TODO'
          })
      }
    }
    
    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(TodoItem)
    

    在组件中,我可以调用 this.props.destroyTodo() 所以它执行 dispatch(...) 在函数中。

    这是根据手册(如果是功能):

    对象。

    将作为参数接收dispatch,并应返回一个对象full 使用dispatch来分派操作的函数。

    充满了动作创造者,每个动作创造者都会变成一个 调用时自动调度其操作的属性函数。

    但是我很难理解现有的代码 工作 链式箭头函数(另一层函数):

    export const createBillingRun = id => dispatch => {
        $.ajax({
            type: 'POST',
            url: `/api/billing/billingtypes/${id}/createrun/`,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        }).done(() => dispatch(pollBillingRuns(id)));
    };
    

    我在这里转换成传统语法:

    export const createBillingRun = function(id) {
        return function(dispatch){
             $.ajax({
                type: 'POST',
                url: `/api/billing/billingtypes/${id}/createrun/`,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
            }).done(() => dispatch(pollBillingRuns(id)));
        }
    }
    

    然后将此函数映射到redux中 connect

    export default connect(
        {...},
        {
            createBillingRun
        },
    )(ThePage);
    

    根据以上代码, createBillingRun 返回一个额外的函数层,所以如果我执行 createBillingRun(123) ,它将返回一个接受 dispatch 作为参数,这与传递到 连接 . 那么谁在执行内部功能呢?

    有人能帮我理解为什么链式箭头函数会起作用吗?

    2 回复  |  直到 6 年前
        1
  •  4
  •   CodeDraken    6 年前

    只有安装了Redux Thunk时,这才有效。它是一个中间件,当您返回一个函数时,它会看到,传递函数分派并调用它。

    https://github.com/reduxjs/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;
    
        2
  •  1
  •   Galupuf    6 年前

    当你的 mapDispatchToProps 返回一个对象,“假定它是Redux操作创建者。”( https://github.com/reduxjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

    https://redux.js.org/basics/actions )

    https://github.com/reduxjs/redux-thunk )

    import ReduxThunk from 'redux-thunk'
    
    ...
    
    const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);