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

Zac*_*ach 3 javascript reactjs arrow-functions react-redux

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

具有以下功能:

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

为什么我们需要多个箭头?为什么lead在一组括号中而dispatchandgetState在另一组括号中?这种来自 Python 的语法非常令人困惑且不直观。

谢谢你的帮助!

T.J*_*der 5

addLead是一个返回函数的函数。这是使用函数体语法而不是简洁的主体语法实现的相同内容,这可能会更清晰:

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

因此,您可以调用以获取与其绑定的addLead函数:lead

const f = addLead("some lead");
Run Code Online (Sandbox Code Playgroud)

...然后根据需要使用dispatchand调用它:state

f("dispatch", "state");
Run Code Online (Sandbox Code Playgroud)

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

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

这是:

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