JS中多参数多箭头函数的困惑

Confusion about multi-parameter multi-arrow functions in JS

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

具有以下功能:

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

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

感谢您的帮助!

addLead 是一个函数,return 是一个函数。这里同样使用函数体语法代替简洁的体语法,这样可能更清晰:

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 returns 不是 return 调用 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(........);
    };
};

是闭包函数。这意味着它需要一个变量和 returns 一个可以让您访问该变量的函数。

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()
  }
}