React Hooks - 使用 useState 与仅使用变量 [英] React Hooks - using useState vs just variables

查看:101
本文介绍了React Hooks - 使用 useState 与仅使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React Hooks 为我们提供了 useState 选项,我总是看到 Hooks 与 Class-State 的比较.但是 Hooks 和一些常规变量呢?

例如

function Foo() {让 a = 0;一 = 1;返回<div>{a}</div>;}

我没有使用 Hooks,它会给我相同的结果:

function Foo() {const [a, setA] = useState(0);如果 (a != 1) setA(1);//避免无限循环返回<div>{a}</div>;}

那么有什么不同呢?在这种情况下使用 Hooks 会更加复杂......那么为什么要开始使用它呢?

解决方案

原因是如果你 useState 它会重新渲染视图.变量本身只会改变内存中的位,应用的状态可能会与视图不同步.

比较这个例子:

function Foo() {const [a, setA] = useState(0);return 

setA(a + 1)}>{a}

;}函数 Foo() {让 a = 0;return

a + 1}>{a}</div>;}

在这两种情况下,a 在点击时都会发生变化,但只有当您使用 useState 时,视图才能正确显示 a 的当前值.

React Hooks give us useState option, and I always see Hooks vs Class-State comparisons. But what about Hooks and some regular variables?

For example,

function Foo() {
    let a = 0;
    a = 1;
    return <div>{a}</div>;
}

I didn't use Hooks, and it will give me the same results as:

function Foo() {
    const [a, setA] = useState(0);
    if (a != 1) setA(1); // to avoid infinite-loop
    return <div>{a}</div>;
}

So what is the diffrence? Using Hooks even more complex for that case...So why start using it?

解决方案

The reason is if you useState it rerenders the view. Variables by themselves only change bits in memory and the state of your app can get out of sync with the view.

Compare this examples:

function Foo() {
    const [a, setA] = useState(0);
    return <div onClick={() => setA(a + 1)}>{a}</div>;
}

function Foo() {
    let a = 0;
    return <div onClick={() => a + 1}>{a}</div>;
}

In both cases a changes on click but only when you use useState the view correctly shows a's current value.

这篇关于React Hooks - 使用 useState 与仅使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆