18号面试了杭州的又拍云,其中面试官问了React函数组件和类组件之间的区别,当时我只回答了有无生命周期、有无this以及state,面试完后,顿时感觉回答的很笼统,很拉,用React这么久了,连函数组件和类组件的区别都说不准,着实拉了,所以今天得空总结总结自己对于函数组件和类组件的区别:
React是基于组件的声明式UI库,其中关键词 组件 和 声明式,今天就来说说组件
Component(组件)可以是类组件(class component)也可以是函数组件(function component)
定义组件:
1.类组件:
类组件使用了ES6的class 来定义组件:
1 class Welcome extends React.Component {
2 render() {
3 return <h1>Hello, {this.props.name}</h1>;
4 }
5 }
2.函数组件:
通过编写JavaScript函数方式来定义组件:
1 function Welcome(props) {
2 return <h1>Hello, {props.name}</h1>;
3 }
组件传参:
例:传入一个参数'hello,world',
1.类组件:需要this来引用
1 class ClassComponent extends React.Component {
2 render() {
3 const { name } = this.props;
4 return <h1>Hello, { name }</h1>;
5 }
6 }
2.函数组件:作为函数参数传递
1 const FunctionalComponent = ({ name }) => {
2 return <h1>Hello, {name}</h1>;
3 };
state&生命周期:
state:众所周知,在 React 项目中,我们无法避免处理state变量。以前,处理state只能在类组件中进行,但从 React 16.8开始,引入了 React Hook useState,允许开发人员编写有state的函数组件。
我们要做一个简单的计数器,从0开始,点击一次按钮就会将计数加1。
1.类组件:
1 class ClassComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 count: 0
6 };
7 }
8
9 render() {
10 return (
11 <div>
12 <p>count: {this.state.count} times</p>
13 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
14 Click
15 </button>
16 </div>
17 );
18 }
19 }
2.函数组件:
1 const FunctionalComponent = () => {
2 const [count, setCount] = React.useState(0);
3
4 return (
5 <div>
6 <p>count: {count}</p>
7 <button onClick={() => setCount(count + 1)}>Click</button>
8 </div>
9 );
10 };
生命周期:只存在于类组件中:
1.constructor(): ①初始化内部的state ②为事件处理函数绑定实例
2.componentDidMount() : 会在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。如需通过网络请求获取数据,此处是实例化请求的好地方。
3.componentDidUpdate(): 会在更新后会被立即调用。首次渲染不会执行此方法。
4.componentWillUnmount():会在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作,例如,清除 timer,取消网络请求或清除在 `componentDidMount()` 中创建的订阅等。
获取渲染时的值:
zhuanlan.zhihu.com/p/104126843,可以参考这篇文章