简体   繁体   English

Github上的Redux ToDo示例

[英]Redux ToDo Example on Github

I am going through the Redux documentation and starting with the Todo Example here: 我正在浏览Redux文档,并从此处的Todo示例开始:

https://github.com/reactjs/redux/tree/master/examples/todos https://github.com/reactjs/redux/tree/master/examples/todos

It works fine. 工作正常。 There is something basic that I don't understand though. 有一些我不了解的基本知识。 Following is a code snippet from the index.js file that defines the actions: 以下是index.js文件中定义操作的代码段:

let nextTodoId = 0
export const addTodo = (text) => ({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})

The entire file can be seen at the following URL: 可以在以下URL看到整个文件:

https://github.com/reactjs/redux/blob/master/examples/todos/src/actions/index.js https://github.com/reactjs/redux/blob/master/examples/todos/src/actions/index.js

As you can see, the variable nextTodoId is initialized outside the 'addtodo' function. 如您所见,变量nextTodoId在'addtodo'函数之外进行了初始化。 I am wondering how is it that the 'nextTodoId' variable does not get reset to 0 every-time the function is called? 我想知道每次调用该函数时'nextTodoId'变量不会重置为0是怎么回事?

Can someone please explain? 有人可以解释一下吗?

Thanks for your time. 谢谢你的时间。

nextTodoId is owned by a scope outside of addTodo. nextTodoId由addTodo之外的作用域拥有。 Therefore that variable can be accessed from addTodo but is not owned by it so even when you return from the function the variable will exist. 因此,可以从addTodo访问该变量,但该变量不属于该变量,因此即使您从该函数返回,该变量也将存在。

That's a function of how import and require work in Javascript modules. 这是importrequire在Javascript模块中如何工作的功能。 The module loader runs the code in each imported/required file once. 模块加载器在每个导入/需要的文件中运行一次代码。 After that, it caches the result, and any other modules that import or require that file in the future get the cached version. 之后,它将缓存结果,以后导入或需要该文件的所有其他模块将获取缓存的版本。

So nextTodoId is only initialized the first time that file is import ed/ require d. 因此, nextTodoId仅在第一次import文件或require d时才初始化。

The nextTodoId variable is declared in the same scope (module scope) as addTodo function. 在与addTodo函数相同的作用域(模块作用域)中声明nextTodoId变量。 Content inside a module file is treated as if is enclosed in a scope closure, just like happens with function closures. 模块文件中的内容被视为包含在作用域闭包中,就像函数闭包一样。 Modules are evaluated only once, even when they are imported multiple times. 模块仅评估一次,即使多次导入也是如此。 Therefore, the nextTodoId variable is declared only once and every time the addTodo function is called will use the current value of nextTodoId variable. 因此,仅声明一次nextTodoId变量,并且每次调用addTodo函数时都将使用nextTodoId变量的当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM