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

查看:43
本文介绍了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> {{状态.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 的一种情况.如果要更新两个状态( a b ),则必须调用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',
});

但是,这种方法的缺点是,如果您只希望仅更新其中一个属性,则必须散布整个状态对象(贷记到

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天全站免登陆