简体   繁体   English

React Hooks 和 useState 的使用

[英]React Hooks and the use of useState

I have a component with some states.我有一个带有一些状态的组件。 What is the different between之间有什么不同

Example 1:示例 1:

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

and Example 2:和示例 2:

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

Example 2 is more verbose.示例 2 更加冗长。 But all the hooks example I see on the internet prefer the Example 2's style.但是我在互联网上看到的所有钩子示例都喜欢示例 2 的样式。 Is there any performance penalty or best practice that preferred one or another??是否有任何性能损失或最佳实践偏好其中之一?

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>两种方法都以相同的最终目标结束,您将创建一个呈现以下元素的组件: <div>{{ state.a }} and {{ state.b }}</div>

However, here's a scenario for Example 1 .但是,这是示例 1的场景。 If you wish to update both states( a , and b ) , you will have to call 2 different methods to update the state:如果您希望更新两个状态( ab ),则必须调用 2 种不同的方法来更新状态:

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

On the other hand, for Example 2 , you will only need to call 1 method to update the state.另一方面,对于示例 2 ,您只需要调用 1 方法来更新状态。

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).但是,这种方法的缺点是,如果您只想更新一个属性,则必须传播整个状态对象(归功于@DrewReese指出了这一点)。 For instance, if you want to update only b ,例如,如果您只想更新b

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

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.话虽如此,说示例 1 的“性能”较差是不准确的,因为如果在同一事件处理程序中调用更新,React 将批量更新,并导致单次重新渲染。

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

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