[英]When to use stateless component in react
I know the difference between stateless
and statefull components
in react application. 我知道反应应用程序中
stateless
和statefull components
之间的区别。 I want to know what is the efficient way to use stateless
and statefull components
together. 我想知道将
stateless
和statefull components
一起使用的有效方法是什么。 Is there any performance benefit of using the one over the other in any particular situation 在任何特定情况下使用一个在另一个上是否有任何性能优势
You should default to using stateless components. 您应该默认使用无状态组件。 Since they use no state, it's very easy to tell when a component should be re-rendered, since they will display the same thing if their props do not change.
由于它们不使用状态,因此很容易判断何时应该重新渲染组件,因为如果它们的道具没有改变,它们将显示相同的内容。
You should use stateful components when you need to use setState
or when you need to use lifecycle hooks. 当您需要使用
setState
或需要使用生命周期钩子时,应该使用有状态组件。
In theory there could be performance benefits for using stateless components due to the fact they are pure functions (or should be pure functions), but I don't have any hard numbers for that. 从理论上讲,使用无状态组件可能会带来性能优势,因为它们是纯函数(或者应该是纯函数),但我没有任何硬数据。
Class components (that have state) can be used when you want to store some local data inside a component. 当您想要在组件中存储一些本地数据时,可以使用类组件(具有状态)。 For eg -
例如 -
import React from 'react'
function handleInc (state, props) {
return {
count: state.count + 1
}
}
class App extends React.Component {
state = {
count: 0
}
handleClick = () => {
this.setState(handleInc);
}
render() {
return (
<div>
<button onClick={this.handleClick}>Increase</button>
<p>{this.state.count}</p>
</div>
);
}
}
These components are also called smart containers or components because they hold all the logic for modifying the UI based on the state (Redux pattern). 这些组件也称为智能容器或组件,因为它们具有基于状态(Redux模式)修改UI的所有逻辑。
Functional components have no state or any local data. 功能组件没有状态或任何本地数据。 These components can be used to update some UI by passing down the props from the parent component.
这些组件可用于通过从父组件传递道具来更新某些UI。
<Child data={this.state.count} />
Functional components have their own advantages like : 功能组件有各自的优点,如:
They are easy to test. 它们很容易测试。
They are easy to understand. 它们很容易理解。
Performance 性能
this
keyword. this
关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.