React Hooks 和 useState 的使用 [英] React Hooks and the use of useState

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

问题描述

我有一个包含一些状态的组件.有什么区别

I have a component with some states. What is the different between

示例 1:

function CompA() {
  [a, setA] = useState(0);
  [b, setB] = useState("Test");
  return (<div>{{ a }} and {{ b }}</div>);
}

和示例 2:

function CompA() {
  [state, setState] = useState({a: 0, b: "Test"});
  return (<div>{{ state.a }} and {{ state.b }}</div>);
}

示例 2 更详细.但是我在网上看到的所有 hooks 示例都更喜欢示例 2 的风格.是否有任何性能损失或最佳实践偏爱一种或另一种?

Example 2 is more verbose. But all the hooks example I see on the internet prefer the Example 2's style. Is there any performance penalty or best practice that preferred one or another??

推荐答案

这两种方法的最终目标相同,您将创建一个呈现以下元素的组件:<div>{{ state.a }} 和 {{ state.b }}</div>

Both approaches will end up with the same end goal, whereby you will create a component that renders the following element: <div>{{ state.a }} and {{ state.b }}</div>

但是,这是示例 1 的场景.如果您希望同时更新两个状态(ab),则必须调用 2 种不同的方法来更新状态:

However, here's a scenario for Example 1. If you wish to update both states(a, and b) , you will have to call 2 different methods to update the state:

setA(1);
setB('bbbb');

另一方面,对于示例 2,您只需调用 1 个方法即可更新状态.

On the other hand, for Example 2, you will only need to call 1 method to update the state.

setState({
  a: 1,
  b: 'bbb',
});

但是,这种方法的缺点是,如果您只想更新其中一个属性,则必须传播整个状态对象(归功于 @DrewReese 指出这一点).例如,如果您只想更新 b

However, the downside of this approach is that, you will have to spread the entire state object if you only wish to update only one of the properties (credit goes to @DrewReese for pointing this out). For instance, if you want to update only b,

setState({
  ...state, 
  b: 'bbb',
});

话虽如此,说示例 1 的性能"较差是不准确的,因为如果在同一个事件处理程序中调用更新,React 会批量更新,并导致一次重新渲染.

That being said, it will not be accurate to state that Example 1 is less "performant", as React will batch the updates if they are called within the same event handler, and cause a single re-render.

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

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