Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - 在反应挂钩,函数语句或const中定义函数? [重复](Define function in react hooks, function statement or const? [duplicate])

When I have a react hook and inside of it I want to define a function in it, would I better use(当我有一个反应钩子并在其中时,我想在其中定义一个函数,我最好使用)

useEffect(() => {
    //...
    function handler() {}
    //...
}, []);

or the newer const declaration(或较新的const声明)

useEffect(() => {
    //...
    const handler = () => {}
    //...
}, []);

Are both exactly equivalent or are there differences in how Javascript handles these things?(两者完全相同还是Javascript处理这些事情的方式不同?)

If I define a const, it's only valid within the current scope, while defining a function would be valid elsewhere, is this true?(如果我定义一个const,则它仅在当前范围内有效,而定义一个函数在其他地方将有效,这是真的吗?)

Does react need the functions accessible in different scopes or are they staying local in the current hook scope?(React是否需要在不同作用域中可访问的功能,还是在当前的钩子作用域中保持局部功能?)

  ask by Supertyp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since THIS is apart of the past by using React Hooks, you can use them both :) it's just syntax sugar es6.(因为是除了以往的使用阵营钩子,你可以使用这两个:)它只是语法糖ES6。)

If you want to go deeper on their differences you can use this article: https://www.freecodecamp.org/news/constant-confusion-why-i-still-use-javascript-function-statements-984ece0b72fd/ (there are plenty of more)(如果您想进一步了解它们之间的差异,可以使用以下文章: https : //www.freecodecamp.org/news/constant-confusion-why-i-still-use-javascript-function-statements-984ece0b72fd/ (有还有更多))

BUT IN REACT HOOKS THEY HAVE THE SAME SCOPE(但是,它们的作用范围相同)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...