【问题标题】:Chained Arrow function syntax链式箭头函数语法
【发布时间】:2017-07-17 14:44:46
【问题描述】:
const fetch = url => dispatch => {
  // ...
}

export const fetchQuestions = tag => (dispatch) => {
  return dispatch(fetch(tag));
};

fetch 函数中的dispatch 是什么? url 是第一个也是单个参数 fetch 函数。但是这里的dispatch 是什么?

【问题讨论】:

  • 这叫做柯里化。谷歌一下。
  • 您可以看到它的实际效果。网上有一些 es6 => es5 转换器。试试这个,例如:es6console.com。将代码粘贴到编辑器中,然后单击“转换”
  • 本打算根据您的代表对此投反对票,但我意识到您并没有像 JavaScript 那样参与。

标签: javascript reactjs


【解决方案1】:

这相当于一个函数返回另一个函数。 IE。这个

const fetch = url => dispatch => {
    // ...
}

等价于

const fetch = function(url) {
    return function(dispatch) {
        // ... 
    }
}

类似

export const fetchQuestions = tag => (dispatch) => {
  return dispatch(fetch(tag));
};

等价于

export const fetchQuestions = function(tag) {
    return function(dispatch) {
        return dispatch(fetch(tag));
    }
};

【讨论】:

  • 为什么需要嵌套这样的函数?
【解决方案2】:

dispatchurl => ... 函数返回的函数的第一个也是单个参数。使用正常的函数语法,它将是

const fetch = function(url) {
    return function(dispatch) {...}
}

【讨论】:

    【解决方案3】:

    fetch 是一个命名函数表达式,它采用url 参数并返回一个采用dispatch 参数的新函数。

    您可以使用传统的函数语法重写:

    const fetch = function (url) {
      return function(dispatch) {
        // ...
      }
    }
    

    【讨论】:

      【解决方案4】:

      它是returns another function 的一种更短的编写函数的方法。参数 urldispatchcurryed function 的参数

      function fetch(url) {
          return function(dispatch) {
               ....
          }
      }
      

      或使用箭头语法为

      const fetch = (url) => {
          return (dispatch) => {
              // ... 
          }
      }
      

      类似地,您会将fetchQuestion 写成

      export function fetchQuestions(tag) {
           return function(dispatch){
                  return dispatch(fetch(tag));
           }
      }
      

      或使用箭头语法为

      export const fetchQuestions = (tag) => {
          return (dispatch) =>  {
              return dispatch(fetch(tag));
          }
      };
      

      【讨论】:

        猜你喜欢
        • 2018-06-08
        • 1970-01-01
        • 2021-04-24
        • 2017-08-15
        • 2017-03-05
        • 2023-02-22
        • 2016-06-03
        • 2017-10-14
        • 1970-01-01
        相关资源
        最近更新 更多