简体   繁体   English

React Native const vs let vs var in Functional Components

[英]React Native const vs let vs var in Functional Components

This is a broader question about the use of different variable declarations in react native functional components (as opposed to class components), specially the use of let vs const, and how they are effected by renders and such.这是一个更广泛的问题,关于在反应本机功能组件(与类组件相反)中使用不同的变量声明,特别是 let 与 const 的使用,以及它们如何受渲染等影响。 For this question, when I say 'render' or 're-render' I am talking about the execution of the render function (like 'MyFunctionalComponent' below), not necessarily a UI update/change.对于这个问题,当我说“渲染”或“重新渲染”时,我指的是渲染函数的执行(如下面的“MyFunctionalComponent”),不一定是 UI 更新/更改。

From my understanding, unlike plain js, a const variable is not exactly 'constant' in react/react native, and can be changed (with hooks?) like so:根据我的理解,与普通 js 不同,const 变量在 react/react native 中并不完全是“常量”,并且可以像这样更改(使用钩子?):

export default function MyFunctionalComponent() {

    const [test, setTest] = useState(false);

    const testFunction = () => { //some sort of function, maybe called by a button press
        setTest(true); //this can change test, but something like 'test = true' throws an error
    }
}

However let can take on similar behavior from my understanding:但是,根据我的理解,让我们可以采取类似的行为:

export default function MyFunctionalComponent() {


    let test = false

    const testFunction = () => { //some sort of function, maybe called by a button press
        test = true;
    }
}

However, most react native examples and tutorials and such I have looked at, always seem to use the const syntax, even though it seems to involve much more code.然而,大多数 react native 示例和教程等我看过,似乎总是使用 const 语法,即使它似乎涉及更多代码。 Why?为什么? Personal preference, or necessity?个人喜好,还是必要性? Does the const way of doing things somehow re-render/re-call MyFunctionalComponent with a new value for the const variable? const 的做事方式是否以某种方式重新渲染/重新调用 MyFunctionalComponent 并为 const 变量赋予一个新值?

Next, I'm not sure the exact behavior that is causing this, but sometimes when using the const syntax inside the functional component, the variables change and save state between render calls, and sometimes, a const variable is reset to its default state every time the render is called.接下来,我不确定导致这种情况的确切行为,但有时在功能组件中使用 const 语法时,变量会在渲染调用之间更改并保存状态,有时,const 变量会在每个时间重置为其默认状态调用渲染的时间。 (I know this part is vague, so feel free to ignore it if there is not enough detail) Why does this happen? (我知道这部分是模糊的,所以如果没有足够的细节可以忽略它)为什么会发生这种情况?

Similarly, I have seen different behavior when consts are created outside of the functional component instead of within... does scope work as you would expect with these?同样,当在函数组件之外而不是在函数组件内部创建 const 时,我看到了不同的行为……作用域是否像您期望的那样工作? Are they (still?) re-instantiated on new render calls?他们(仍然?)在新的渲染调用中重新实例化了吗? Does 'setState' call an re-render? 'setState' 会调用重新渲染吗? Shortening the previous question, why do some of my const's preserve their state on re-renders, while some seem to reset to their defaults?缩短上一个问题,为什么我的一些常量在重新渲染时保留其状态,而有些似乎重置为默认值?

Where does var fall into this, does it act the same as in regular js, or is it affected by react as well? var 在哪里,它是否与常规 js 中的行为相同,还是也受 react 的影响? (I feel like I have a grasp of the differences in these variable declarations in regular js, but this const behavior with react making me question it all). (我觉得我已经掌握了常规 js 中这些变量声明的差异,但是 react 的这种 const 行为让我质疑这一切)。

So overall the question is basically, what are the differences/advantages of let, var, and const, specifically in react/react native, and how do those differ from regular javascript?所以总的来说,问题基本上是,let、var 和 const 的区别/优势是什么,特别是在 react/react native 中,它们与常规 javascript 有何不同?

Lastly, does it differ between class components and functional components in react native?最后,它在 React Native 中的类组件和功能组件之间有区别吗?

Thank you for reading this long question.感谢您阅读这么长的问题。

Personal preference, or necessity?个人喜好,还是必要性?

Preference and style only.仅偏好和风格。

Using const to declare a stateful variable instead of var or let makes the intent of the code clearer.使用const来声明一个有状态变量而不是varlet使代码的意图更加清晰。 It's not necessary - pretty much all components you see would work just as well if they used var or let - but it introduces a slight possibility of confusion from those reading the code.这不是必需的——你看到的几乎所有组件如果使用varlet也能正常工作——但它会给阅读代码的人带来一些混淆的可能性。

React is written in JavaScript. React 是用 JavaScript 编写的。 Stateful variables in React, declared with const , cannot be reassigned, just like in ordinary JavaScript. React 中的有状态变量,用const声明,不能重新赋值,就像在普通 JavaScript 中一样。 The key you're missing is that the component function is called again every time there's a re-render, resulting in the call of the useState function returning a different value.您缺少的关键是每次重新渲染都会再次调用组件函数,从而导致调用useState函数返回不同的值。

For quick example of how this could work in vanilla JS with const and calling a function multiple times:有关这如何在带有const并多次调用函数的 vanilla JS 中工作的快速示例:

 let i = 0; const getI = () => i; const fn = () => { const theValue = getI(); console.log(theValue); i++; setTimeout(fn, 1000); }; fn();

It's not that the variable gets reassigned (which would be forbidden due to the use of const ), it's that the whole function runs again, resulting in a new value being assigned to the variable declared with const at the moment of its new initialization.并不是变量被重新分配(由于使用const会被禁止),而是整个函数再次运行,导致在新初始化时为用const声明的变量分配一个新值。

Next, I'm not sure the exact behavior that is causing this, but sometimes when using the const syntax inside the functional component, the variables change and save state between render calls, and sometimes, a const variable is reset to its default state every time the render is called.接下来,我不确定导致这种情况的确切行为,但有时在功能组件中使用 const 语法时,变量会在渲染调用之间更改并保存状态,有时,const 变量会在每个时间重置为其默认状态调用渲染的时间。 (I know this part is vague, so feel free to ignore it if there is not enough detail) Why does this happen? (我知道这部分是模糊的,所以如果没有足够的细节可以忽略它)为什么会发生这种情况?

You may be referring to the stale closure issue.您可能指的是过时的关闭问题。 This can happen if the variable binding that results in a difference being seen is from a prior render, rather than the current render.如果导致看到差异的变量绑定来自先前的渲染,而不是当前的渲染,则可能会发生这种情况。

For a quick example of what that might look like in vanilla JS, adapting from the above snippet, I'll add a timeout on the first render, which will result in only the i from the first render being used:对于在 vanilla JS 中可能是什么样子的快速示例,根据上述代码段改编,我将在第一次渲染时添加超时,这将导致仅使用来自第一次渲染的i

 let i = 0; const getI = () => i; const fn = () => { const theValue = getI(); console.log(theValue); if (theValue === 0) { // first render setTimeout(() => { console.log('Timeout from first render running, sees a theValue of:', theValue); }, 5000); } i++; setTimeout(fn, 1000); }; fn();

Similarly, I have seen different behavior when consts are created outside of the functional component instead of within... does scope work as you would expect with these?同样,当在函数组件之外而不是在函数组件内部创建 const 时,我看到了不同的行为……作用域是否像您期望的那样工作? Are they (still?) re-instantiated on new render calls?他们(仍然?)在新的渲染调用中重新实例化了吗?

Depends on what block that variable is in. If it's in another component, it may get re-initialized.取决于该变量所在的块。如果它在另一个组件中,它可能会被重新初始化。 If it's not in another component, then it might not be.如果它不在另一个组件中,那么它可能不是。 For example, it's common to have a module that exports a component with some absolutely unchanging const values that all the components use declared up top, eg例如,这是常见的有一个模块是出口组件与一些绝对不变的const的值,所有的组件都使用声明向上顶,例如

const apiKey = 'someApiKey';
export const ApiInterface = () => {
  // ...
};

With regards to const vs let and var specifically, the problem with let and var is that they permit reassignment - but the only right way to change a stateful variable in React is to call the state setter, not to reassign the variable.至于const VS letvar而言,这个问题letvar的是,他们允许重新分配-但要改变一个状态变量作出反应的唯一正确途径是调用状态决定部,而不是重新分配变量。 Calling the state setter is what will result in a re-render;调用状态设置器会导致重新渲染; reassigning a variable will not result in a re-render, and reassigning a variable will result in the assigned value being lost on the next re-render.重新分配变量不会导致重新渲染,重新分配变量将导致分配的值在下一次重新渲染时丢失。 So, it's a good idea to be perfectly clear that stateful variables should not be reassigned.因此,完全清楚不应重新分配有状态变量是一个好主意。

Lastly, does it differ between class components and functional components in react native?最后,它在 React Native 中的类组件和功能组件之间有区别吗?

Yes, in class components, state is held as a property of the instance (the this ).是的,在类组件中,状态作为实例的属性( this )。 The state is no longer a standalone const identifier, but a property of a larger object, so there's no const vs let vs var for stateful values in class components - unless you extract values from state and put them into normal standalone variables yourself, in which case they behave just like any other standalone variable.状态不再是一个独立的const标识符,而是一个更大对象的属性,所以对于类组件中的有状态值,没有const vs let vs var - 除非您从状态中提取值并将它们自己放入普通的独立变量中,其中如果它们的行为就像任何其他独立变量一样。

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

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