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',
<Component name="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()
中創建的訂閱等。
獲取渲染時的值:
https://zhuanlan.zhihu.com/p/104126843,可以參考這篇文章