React
组件可以使用函数组件和类组件两种方式来定义。下面是它们之间的一些区别:
JavaScript
函数,而类组件则是一个 ES6
类。js// 类组件
class MyComponent extends React.Component {
render() {
return <div>Hello World!</div>;
}
}
// 函数组件
function MyComponent() {
return <div>Hello World!</div>;
}
组件状态:类组件可以使用 state
来保存组件的状态,并使用 this.setState()
方法来更新状态。而函数组件没有自己的状态,只能使用 State Hook
进行状态管理
生命周期:函数组件没有生命周期方法,只能使用 React Hook
来模拟类组件的生命周期行为。类组件可以使用常规的生命周期方法,例如 componentDidMount()
和 componentDidUpdate()
等。
js// 类组件
class MyComponent extends React.Component {
componentDidMount() {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
}
render() {
return <div>Hello World!</div>;
}
}
// 函数组件
function MyComponent() {
useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
}, []);
return <div>Hello World!</div>;
}
性能:函数组件比类组件具有更好的性能,因为它们没有实例化过程,不需要绑定 this
,且没有生命周期的开销。
this
指向:在类组件中,this
关键字指向组件的实例对象。可以使用 bind
方法来绑定方法中的 this
指向。在函数组件中,由于没有实例对象的概念,this
关键字指向的是全局对象(如window或global)。
本文作者:叶继伟
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!