gpt4 book ai didi

javascript - thunk 和闭包的区别

转载 作者:数据小太阳 更新时间:2023-10-29 04:13:17 27 4
gpt4 key购买 nike

我以为我知道什么是闭包,但我不太确定是否阅读了一些有关 React 的文章。

下面的函数是“thunk”吗?(对我来说这是一个闭包,我从一篇关于 React https://spin.atomicobject.com/2016/10/05/form-validation-react/ 的博客文章中得到了这个)

作者解释:“接下来,我们来看ruleRunner函数,ruleRunner是一个thunk,或者说是一个返回函数的函数。”

export const ruleRunner = (field, name, ...validations) => {
return (state) => {
for (let v of validations) {
let errorMessageFunc = v(state[field], state);
if (errorMessageFunc) {
return {[field]: errorMessageFunc(name)};
}
}
return null;
};
};

相反,我认为 thunk 是“一个包含所有上下文(状态、函数等)的函数,以便将来执行某种逻辑。”来自:http://www.austinstory.com/what-is-a-thunk-in-javascript/

const add = (x,y) => x + y;

const thunk = () => add(1,2);

thunk() // 3

所以对我来说,第一篇文章的作者是错误的,他给出的是闭包的描述和示例,而不是 thunk。但我可能错了,这就是我问这个问题的原因。

第一篇文章作者关于什么是 thunk 的说法是错误的吗?说 thunk 是一种特定类型的闭包是否正确?它包含执行执行所需的所有上下文(状态、函数等) future 的某种逻辑。”

最佳答案

"ruleRunner is a thunk, or a function that returns a function."

不,那是垃圾。返回函数的函数称为 higher-order function . 返回 函数通常是 closure .

I thought a thunk was "a function that contains all of the context (state, functions, etc) it will need in order to carry out some sort of logic in the future."

是的,这听起来很合理。这类似于闭包,但是闭包通常需要一些进一步的参数,而 thunk不需要 - 它只需要启动即可执行。

关于javascript - thunk 和闭包的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com