【问题标题】:Confusion about multi-parameter multi-arrow functions in JS [duplicate]关于JS中的多参数多箭头函数的困惑[重复]
【发布时间】:2020-07-03 02:53:21
【问题描述】:

我目前正在阅读有关 React 的教程,但我无法理解这些箭头函数的语法,尤其是在有多个参数的情况下。我来自 Python,还在学习 JS,所以请记住这一点。

具有以下功能:

// ADD LEAD
export const addLead = (lead) => (dispatch, getState) => {
    axios
        .post('/api/leads/', lead, tokenConfig(getState))
        .then(........)
}

为什么我们需要多个箭头?为什么lead 在一组括号中,而dispatchgetState 在另一组括号中?来自 Python 的这种语法令人难以置信的混乱和不直观。

感谢您的帮助!

【问题讨论】:

标签: javascript reactjs react-redux arrow-functions


【解决方案1】:

addLead 是一个返回函数的函数。这里使用函数体语法而不是简洁的体语法是一样的,这可能更清楚:

export const addLead = (lead) => {
    return (dispatch, getState) => {
        axios
            .post('/api/leads/', lead, tokenConfig(getState))
            .then(........)
    };
}

所以你可以调用addLead 来获得一个绑定了lead 的函数:

const f = addLead("some lead");

...然后酌情使用dispatchstate 调用它:

f("dispatch", "state");

旁注:有点奇怪(没有更多上下文)addLead 返回的函数不返回调用axios 的结果。我本来希望它是:

export const addLead = (lead) => (dispatch, getState) => 
    axios
        .post('/api/leads/', lead, tokenConfig(getState))
        .then(........);

这是:

export const addLead = (lead) => {
    return (dispatch, getState) => {
        return axios
            .post('/api/leads/', lead, tokenConfig(getState))
            .then(........);
    };
};

【讨论】:

    【解决方案2】:

    是闭包函数。这意味着它接受一个变量并返回一个让您可以访问该变量的函数。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

    您的代码基本上转化为以下内容

    export const addLead = function(lead) {
      return function(dispatch, getState) {
    axios
      .post('/api/leads/', lead, tokenConfig(getState))
      .then()
      }
    }

    【讨论】:

      猜你喜欢
      • 2017-04-25
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2015-04-08
      • 1970-01-01
      相关资源
      最近更新 更多