這篇文章翻譯自Medium的一篇文章:Container Componentshtml
選擇這篇文章翻譯的緣由是,在剛接觸React的時候,這篇文章很好的指引我瞭解Container Components模式。react
Container components模式是一款很棒的React模式,對個人代碼影響很大。git
Jason Bonta在React.js大會中說過他們如何在Facebook開發高效的組建。在這個演講中,他提到了container components模式。github
其實原理很簡單:ajax
一個container負責數據的獲取,而後渲染它對應的下級component。就這些而已。json
「對應的」的意思是他們擁有共同的名稱:數據結構
StockWidgetContainer => StockWidget TagCloudContainer => TagCloud PartyPooperListContainer => PartyPooperList
大概就是這個意思。架構
假設咱們須要作一個展現評論的組建。在你不知道container components模式以前,你會把全部的東西都放在一個裏面:oop
// CommentList.js class CommentList extends React.Component { constructor() { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json", dataType: 'json', success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <ul> {this.state.comments.map(renderComment)} </ul>; } renderComment({body, author}) { return <li>{body}—{author}</li>; } }
你的這個組建要同時負責獲取數據和展現數據。固然,這種作法沒有什麼錯的,可是你沒有很好的利用React的一些優點。this
除非在一個如出一轍的使用環境下,你沒法重用CommentList組建。
你的展現組建對須要的數據架構有具體的要求,而PropTypes可以很好地知足這個要求。
展現組建對數據結構有必定的要求,可是卻沒有辦法限制數據類型。若是傳入的json結構發生了改變,那麼組建就會down掉,並不會拋出任何錯誤。
// CommentListContainer.js class CommentListContainer extends React.Component { constructor() { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json", dataType: 'json', success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <CommentList comments={this.state.comments} />; } }
同時,咱們修改一下CommentList讓它能夠接受一個comments的prop。
// CommentList.js class CommentList extends React.Component { constructor(props) { super(props); } render() { return <ul> {this.props.comments.map(renderComment)} </ul>; } renderComment({body, author}) { return <li>{body}—{author}</li>; } }
咱們獲取了不少東西…
咱們分離了數據獲取和數據渲染的邏輯。
咱們讓CommentList變成了可複用的組建。
咱們容許CommentList能夠經過PropTypes來限制props數據個格式。若是props格式出錯,就會報錯。
我是container components模式的忠實簇擁者,它幫助我更好的完成React項目。你們不妨試一試,也能夠觀看這個視屏。一個很棒的模式。
再次聲明:這篇文章翻譯自Medium的一篇文章:Container Components若是要轉載,請至少著名上面的文章出處,謝謝。