国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表

圖片精選

主站蜘蛛池模板: 甘孜| 格尔木市| 岚皋县| 辉南县| 临邑县| 黄石市| 郑州市| 若羌县| 北流市| 永胜县| 商洛市| 怀集县| 剑阁县| 宾川县| 神木县| 山阴县| 宜黄县| 舒城县| 宝鸡市| 莲花县| 札达县| 金门县| 丹江口市| 丹东市| 铜鼓县| 恩平市| 林芝县| 阿克陶县| 鹿泉市| 万盛区| 砚山县| 万山特区| 丹巴县| 观塘区| 留坝县| 乐业县| 蒙山县| 常宁市| 马边| 富蕴县| 峨眉山市|