日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
想知道如何寫出漂亮的React組件嗎?

在Walmart Labs的產(chǎn)品開發(fā)中,我們進行了大量的Code Review工作,這也保證了我有機會從很多優(yōu)秀的工程師的代碼中學習他們的代碼風格與樣式。在這篇博文里我會分享出我最欣賞的五種組件模式與代碼片。不過我首先還是要談?wù)劄槭裁次覀冃枰獔?zhí)著于提高代碼的閱讀體驗。就好像你有很多種方式去裝扮一只貓,如果你把你的愛貓裝扮成了如下這樣子:

成都創(chuàng)新互聯(lián)長期為上千客戶提供的網(wǎng)站建設(shè)服務(wù),團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為萊陽企業(yè)提供專業(yè)的網(wǎng)站建設(shè)、網(wǎng)站設(shè)計,萊陽網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。

你或許可以認為蘿卜青菜各有所愛,但是代碼本身是應(yīng)當保證其可讀性,特別是在一個團隊中,你的代碼是注定要被其他人閱讀的。電腦是不會在意這些的,不管你朝它們?nèi)舆^去什么,它們都會老老實實的解釋,但是你的隊友們可不會這樣,他們會把丑陋的代碼扔回到你的臉上。而所謂的Pretty Components,應(yīng)該包含如下的特性:

  • 即使沒有任何注釋的情況下也易于理解
  • 比亂麻般的代碼有更好的性能表現(xiàn)
  • 更易于進行Bug追溯
  • 簡潔明了,一句頂一萬句

[[201978]]

SFC:Stateless Functional Component

我覺得我們在開發(fā)中經(jīng)常忽略掉的一個模式就是所謂的Stateless Functional Component,不過這是我個人***的React組件優(yōu)化模式,沒有之一。我喜愛這種模式不僅僅因為它們能夠減少大量的模板代碼,而且因為它們能夠有效地提高組件的性能表現(xiàn)??偠灾?,SFC能夠讓你的應(yīng)用跑的更快,長的更帥。

[[201979]]

直觀來看,SFC就是指那些僅有一個渲染函數(shù)的組件,不過這簡單的改變就可以避免很多的無意義的檢測與內(nèi)存分配。下面我們來看一個實踐的例子來看下SFC的具體作用,譬如:

 如果我們用正統(tǒng)的React組件的寫法,可以得出如下代碼:

 
 
 
 
  1. export default class RelatedSearch extends React.Component { 
  2.  
  3.   constructor(props) { 
  4.  
  5.     super(props); 
  6.  
  7.     this._handleClick = this._handleClick.bind(this); 
  8.  
  9.   } 
  10.  
  11.   _handleClick(suggestedUrl, event) { 
  12.  
  13.     event.preventDefault(); 
  14.  
  15.     this.props.onClick(suggestedUrl); 
  16.  
  17.   } 
  18.  
  19.   render() { 
  20.  
  21.     return ( 
  22.  
  23.        
  24.  
  25.         Related Searches: 
  26.  
  27.          
  28.  
  29.           {this.props.relatedQueries.map((query, index) => 
  30.  
  31.             
  32.  
  33.               className="related-search-link" 
  34.  
  35.               onClick={(event) => 
  36.  
  37.                 this._handleClick(query.searchQuery, event)} 
  38.  
  39.               key={index}> 
  40.  
  41.               {query.searchText} 
  42.  
  43.              
  44.  
  45.           )} 
  46.  
  47.          
  48.  
  49.        
  50.  
  51.     ); 
  52.  
  53.   } 
  54.  
  55. }  

而使用SFC模式的話,大概可以省下29%的代碼:

 
 
 
 
  1. const _handleClick(suggestedUrl, onClick, event) => { 
  2.  
  3.   event.preventDefault(); 
  4.  
  5.   onClick(suggestedUrl); 
  6.  
  7. }; 
  8.  
  9. const RelatedSearch = ({ relatedQueries, onClick }) => 
  10.  
  11.    
  12.  
  13.     Related Searches: 
  14.  
  15.      
  16.  
  17.       {relatedQueries.map((query, index) => 
  18.  
  19.         
  20.  
  21.           className="related-search-link" 
  22.  
  23.           onClick={(event) => 
  24.  
  25.             _handleClick(query.searchQuery, onClick, event)} 
  26.  
  27.           key={index}> 
  28.  
  29.           {query.searchText} 
  30.  
  31.          
  32.  
  33.       )} 
  34.  
  35.      
  36.  
  37.    
  38.  
  39. export default RelatedSearch;  

代碼量的減少主要來源兩個方面:

  • 沒有構(gòu)造函數(shù)(5行)
  • 以Arrow Function的方式替代Render語句(4行)

實際上,SFC最迷人的地方不僅僅是其代碼量的減少,還有就是對于可讀性的提高。SFC模式本身就是所謂純組件的一種***實踐范式,而移除了構(gòu)造函數(shù)并且將_handleClick()這個點擊事件回調(diào)函數(shù)提取出組件外,可以使JSX代碼變得更加純粹。另一個不錯的地方就是SFC以Arrow Function的方式來定義了輸入的Props變量,即以O(shè)bject Destructring語法來聲明組件所依賴的Props:

 
 
 
 
  1. const RelatedSearch = ({ relatedQueries, onClick }) => 

這樣不僅能夠使組件的Props更加清晰明確,還能夠避免冗余的this.props表達式,從而使代碼的可讀性更好。

[[201980]]

***,我還想要強調(diào)下雖然我很推崇SFC,不過也不能濫用它。最合適使用SFC的地方就是之前你用純組件的地方。在Walmart Labs中,我們使用Redux來管理應(yīng)用的狀態(tài),也就意味著我們絕大部分的組件都是純組件,也就給了SFC廣闊的應(yīng)用空間。一般來說,有以下特征的組件式絕對不適合使用SFC的:

  • 需要自定義整個組件的生命周期管理
  • 需要使用到refs

Conditional Components

JSX本身不支持if表達式,不過我們可以使用邏輯表達式的方式來避免將代碼切分到不同的子模塊中,大概是如下樣子:

 
 
 
 
  1. render() { 
  2.  
  3.    
  4.  
  5.     {this.props.isGrid 
  6.  
  7.       ?  
  8.  
  9.       : 
  10.  
  11.   
 
  •  
  • }  
  • 這種表達式在二選一渲染的時候很有效果,不過對于選擇性渲染一個的情況很不友好,譬如如下的情況:

     
     
     
     
    1. render() { 
    2.  
    3.    
    4.  
    5.     {this.props.isSoftSort 
    6.  
    7.       ?  
    8.  
    9.       : null 
    10.  
    11.     } 
    12.  
    13.   
     
  •  
  • }  
  • 這樣子確實能起作用,不過看上去感覺怪怪的。我們可以選用另一種更加語義化與友好的方式來實現(xiàn)這個功能,即使用邏輯與表達式然后返回組件:

     
     
     
     
    1. render() { 
    2.  
    3.    
    4.  
    5.     {!!this.props.isSoftSort && 
    6.  
    7.   
     
  •  
  • }  
  • 不過這一點也是見仁見智,每個人按照自己的喜好來就行了。

    Arrow Syntax In React And Redux

    ES2015里包含了不少可口的語法糖,我***的就是那個Arrow Notation。這個特性在編寫組件時很有作用:

     
     
     
     
    1. const SoftSort = ({ hardSortUrl, sortByName, onClick }) => { 
    2.  
    3.   return ( 
    4.  
    5.      
    6.  
    7.       Showing results sorted by both Relevance and {sortByName}. 
    8.  
    9.       
    10.  
    11.         href={`?${hardSortUrl}`} 
    12.  
    13.         onClick={(ev) => onClick(ev, hardSortUrl)}> 
    14.  
    15.         Sort results by {sortByName} only 
    16.  
    17.        
    18.  
    19.     
     
  •  
  •   ); 
  •  
  • };  
  • 該函數(shù)的功能就是返回JSX對象,我們也可以忽略return語句:

     
     
     
     
    1. const SoftSort = ({ hardSortUrl, sortByName, onClick }) => 
    2.  
    3.    
    4.  
    5.     Showing results sorted by both Relevance and {sortByName}. 
    6.  
    7.     
    8.  
    9.       href={`?${hardSortUrl}`} 
    10.  
    11.       onClick={(ev) => onClick(ev, hardSortUrl)}> 
    12.  
    13.       Sort results by {sortByName} only 
    14.  
    15.      
    16.  
    17.   
      

    代碼行數(shù)又少了不少咯!

    [[201981]]

    另一塊我覺得非常適用Arrow Function的地方就是Redux的mapStateToProps函數(shù):

     
     
     
     
    1. const mapStateToProps = ({isLoading}) => { 
    2.  
    3.   return ({ 
    4.  
    5.     loading: isLoading, 
    6.  
    7.   }); 
    8.  
    9. };  

    需要注意的是,如果你返回的是Object,你需要包裹在大括號內(nèi):

     
     
     
     
    1. const mapStateToProps = ({isLoading}) => ({ 
    2.  
    3.   loading: isLoading 
    4.  
    5. });  

    使用Arrow Function優(yōu)化的核心點在于其能夠通過專注于函數(shù)的重要部分而提升代碼的整體可讀性,并且避免過多的模板代碼帶來的噪音。

    合理使用Object Destructing與Spread Attributes

    大的組件往往受困于this.props過長的窘境,典型的如下所示:

     
     
     
     
    1. render() { 
    2.  
    3.   return ( 
    4.  
    5.     
    6.  
    7.       hidePriceFulfillmentDisplay= 
    8.  
    9.        {this.props.hidePriceFulfillmentDisplay} 
    10.  
    11.       primaryOffer={this.props.primaryOffer} 
    12.  
    13.       productType={this.props.productType} 
    14.  
    15.       productPageUrl={this.props.productPageUrl} 
    16.  
    17.       inventory={this.props.inventory} 
    18.  
    19.       submapType={this.props.submapType} 
    20.  
    21.       ppu={this.props.ppu} 
    22.  
    23.       isLoggedIn={this.props.isLoggedIn} 
    24.  
    25.       gridView={this.props.isGridView} 
    26.  
    27.     /> 
    28.  
    29.   ); 
    30.  
    31. }  

    這么多的Props估計看著都頭疼,如果我們要將這些Props繼續(xù)傳入下一層,大概就要變成下面這個樣子了:

     
     
     
     
    1. render() { 
    2.  
    3.   const { 
    4.  
    5.     hidePriceFulfillmentDisplay, 
    6.  
    7.     primaryOffer, 
    8.  
    9.     productType, 
    10.  
    11.     productPageUrl, 
    12.  
    13.     inventory, 
    14.  
    15.     submapType, 
    16.  
    17.     ppu, 
    18.  
    19.     isLoggedIn, 
    20.  
    21.     gridView 
    22.  
    23.   } = this.props; 
    24.  
    25.   return ( 
    26.  
    27.     
    28.  
    29.       hidePriceFulfillmentDisplay={hidePriceFulfillmentDisplay} 
    30.  
    31.       primaryOffer={primaryOffer} 
    32.  
    33.       productType={productType} 
    34.  
    35.       productPageUrl={productPageUrl} 
    36.  
    37.       inventory={inventory} 
    38.  
    39.       submapType={submapType} 
    40.  
    41.       ppu={ppu} 
    42.  
    43.       isLoggedIn={isLoggedIn} 
    44.  
    45.       gridView={isGridView} 
    46.  
    47.     /> 
    48.  
    49.   ); 
    50.  
    51. }  

    暫時不考慮unKnown Props,我們可以使用解構(gòu)賦值來實現(xiàn)這個功能:

     
     
     
     
    1. render() { 
    2.  
    3.   const props = this.props; 
    4.  
    5.   return  
    6.  
    7. }  

    Method Definition Shorthand

    ***這個方法不一定多有用,不過還是能讓你的代碼變得更加漂亮。如果你希望在Object中添加函數(shù),你可以使用ES2015 Method Definition Shorthand來代替?zhèn)鹘y(tǒng)的ES5的表達式,譬如:

    如果你想設(shè)置一個默認的空方法,也可以利用這種方式:

     
     
     
     
    1. ProductRating.defaultProps = { 
    2.  
    3.   onStarsClick() {} 
    4.  
    5. };  

    文章名稱:想知道如何寫出漂亮的React組件嗎?
    本文網(wǎng)址:http://www.5511xx.com/article/djggpeh.html