国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

深入理解React高階組件

2024-05-06 15:26:07
字體:
供稿:網(wǎng)友

1.在React中higher-order component (HOC)是一種重用組件邏輯的高級技術(shù)。HOC不是React API中的一部分。HOC是一個函數(shù),該函數(shù)接收一個組件并且返回一個新組件。在React中,組件是代碼復(fù)用的基本單位。

2.為了解釋HOCs,舉下面兩個例子

CommentList組件會渲染出一個comments列表,列表中的數(shù)據(jù)來自于外部。

class CommentList extends React.Component {  constructor() {   super();   this.handleChange = this.handleChange.bind(this);   this.state = {    // "DataSource" is some global data source    comments: DataSource.getComments()   };  }   componentDidMount() {   // Subscribe to changes   DataSource.addChangeListener(this.handleChange);  }   componentWillUnmount() {   // Clean up listener   DataSource.removeChangeListener(this.handleChange);  }   handleChange() {   // Update component state whenever the data source changes   this.setState({    comments: DataSource.getComments()   });  }   render() {   return (    <div>     {this.state.comments.map((comment) => (      <Comment comment={comment} key={comment.id} />     ))}    </div>   );  } } 

 接下來是BlogPost組件,這個組件用于展示一篇博客信息

class BlogPost extends React.Component {  constructor(props) {   super(props);   this.handleChange = this.handleChange.bind(this);   this.state = {    blogPost: DataSource.getBlogPost(props.id)   };  }   componentDidMount() {   DataSource.addChangeListener(this.handleChange);  }   componentWillUnmount() {   DataSource.removeChangeListener(this.handleChange);  }   handleChange() {   this.setState({    blogPost: DataSource.getBlogPost(this.props.id)   });  }   render() {   return <TextBlock text={this.state.blogPost} />;  } } 

這兩個組件是不一樣的,它們調(diào)用了DataSource的不同方法,并且它們的輸出也不一樣,但是它們中的大部分實(shí)現(xiàn)是一樣的:

1.裝載完成后,給DataSource添加了一個change listener
2.當(dāng)數(shù)據(jù)源發(fā)生變化后,在監(jiān)聽器內(nèi)部調(diào)用setState
3.卸載之后,移除change listener

可以想象在大型應(yīng)用中,相同模式的訪問DataSource和調(diào)用setState會一次又一次的發(fā)生。我們希望抽象這個過程,從而讓我們只在一個地方定義這個邏輯,然后在多個組件中共享。

接下來我們寫一個創(chuàng)建組件的函數(shù),這個函數(shù)接受兩個參數(shù),其中一個參數(shù)是組件,另一個參數(shù)是函數(shù)。下面調(diào)用withSubscription函數(shù)

const CommentListWithSubscription = withSubscription( CommentList, (DataSource) => DataSource.getComments()); const BlogPostWithSubscription = withSubscription( BlogPost, (DataSource, props) => DataSource.getBlogPost(props.id)); 

調(diào)用withSubscription傳的第一個參數(shù)是wrapped 組件,第二個參數(shù)是一個函數(shù),該函數(shù)用于檢索數(shù)據(jù)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 株洲市| 奉化市| 安阳县| 苏尼特右旗| 通城县| 阳高县| 丁青县| 鞍山市| 桂平市| 丰原市| 武乡县| 保山市| 昌宁县| 石河子市| 台中市| 静乐县| 商水县| 祥云县| 昔阳县| 故城县| 凤冈县| 子洲县| 东辽县| 谢通门县| 正蓝旗| 孟津县| 比如县| 儋州市| 尼勒克县| 阿鲁科尔沁旗| 高青县| 法库县| 晋宁县| 双牌县| 广丰县| 清原| 尼勒克县| 峡江县| 宝兴县| 苍南县| 兰西县|