自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

編寫react組件更優(yōu)實(shí)踐

開發(fā) 前端
我最開始學(xué)習(xí)react的時(shí)候,看到過各種各樣編寫組件的方式,不同教程中提出的方法往往有很大不同。當(dāng)時(shí)雖說react這個(gè)框架已經(jīng)十分成熟,但是似乎還沒有一種公認(rèn)正確的使用方法。過去幾年中,我們團(tuán)隊(duì)編寫了很多react組件,我們對(duì)實(shí)現(xiàn)方法進(jìn)行了不斷的優(yōu)化,直到滿意。

編寫react組件***實(shí)踐

我最開始學(xué)習(xí)react的時(shí)候,看到過各種各樣編寫組件的方式,不同教程中提出的方法往往有很大不同。當(dāng)時(shí)雖說react這個(gè)框架已經(jīng)十分成熟,但是似乎還沒有一種公認(rèn)正確的使用方法。過去幾年中,我們團(tuán)隊(duì)編寫了很多react組件,我們對(duì)實(shí)現(xiàn)方法進(jìn)行了不斷的優(yōu)化,直到滿意。

本文介紹了我們在實(shí)踐中的***實(shí)踐方式,希望能對(duì)無論是初學(xué)者還是有經(jīng)驗(yàn)的開發(fā)者來說都有一定的幫助。

在我們開始之前,有幾點(diǎn)需要說明:

  • 我們是用es6和es7語法
  • 如果你不了解展示組件和容器組件的區(qū)別,可以先閱讀這篇文章
  • 如果你有任何建議、問題或者反饋,可以給我們留言

Class Based Components (基于類的組件)

Class based components 有自己的state和方法。我們會(huì)盡可能謹(jǐn)慎的使用這些組件,但是他們有自己的使用場景。

接下來我們就一行一行來編寫組件。

導(dǎo)入CSS

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import ExpandableForm from './ExpandableForm' 
  6.  
  7. import './styles/ProfileContainer.css'  

我很喜歡CSS in JS,但是它目前還是一種新的思想,成熟的解決方案還未產(chǎn)生。我們在每個(gè)組件中都導(dǎo)入了它的css文件。

譯者注:目前CSS in JS可以使用css modules方案來解決,webpack的css-loader已經(jīng)提供了該功能

我們還用一個(gè)空行來區(qū)分自己的依賴。

譯者注:即第4、5行和第1、2行中間會(huì)單獨(dú)加行空行。

初始化state

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import ExpandableForm from './ExpandableForm' 
  6.  
  7. import './styles/ProfileContainer.css' 
  8.  
  9. export default class ProfileContainer extends Component { 
  10.  
  11. state = { expanded: false }  

你也可以在constructor中初始化state,不過我們更喜歡這種簡潔的方式。我們還會(huì)確保默認(rèn)導(dǎo)出組件的class。

propTypes 和 defaultProps

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32.  

propTypes和defaultProps是靜態(tài)屬性,應(yīng)該盡可能在代碼的頂部聲明。這兩個(gè)屬性起著文檔的作用,應(yīng)該能夠使閱讀代碼的開發(fā)者一眼就能夠看到。如果你正在使用react 15.3.0或者更高的版本,使用prop-types,而不是React.PropTypes。你的所有組件,都應(yīng)該有propTypes屬性。

方法

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32.  
  33. handleSubmit = (e) => { 
  34.  
  35. e.preventDefault() 
  36.  
  37. this.props.model.save() 
  38.  
  39.  
  40. handleNameChange = (e) => { 
  41.  
  42. this.props.model.changeName(e.target.value) 
  43.  
  44.  
  45. handleExpand = (e) => { 
  46.  
  47. e.preventDefault() 
  48.  
  49. this.setState({ expanded: !this.state.expanded }) 
  50.  
  51.  

使用class components,當(dāng)你向子組件傳遞方法的時(shí)候,需要確保這些方法被調(diào)用時(shí)有正確的this值。通常會(huì)在向子組件傳遞時(shí)使用this.handleSubmit.bind(this)來實(shí)現(xiàn)。當(dāng)然,使用es6的箭頭函數(shù)寫法更加簡潔。

譯者注:也可以在constructor中完成方法的上下文的綁定:

  1. constructor() { 
  2.  
  3. this.handleSubmit = this.handleSubmit.bind(this); 
  4.  
  5.  

給setState傳入一個(gè)函數(shù)作為參數(shù)(passing setState a Function)

在上文的例子中,我們是這么做的:

  1. this.setState({ expanded: !this.state.expanded }) 

setState實(shí)際是異步執(zhí)行的,react因?yàn)樾阅茉驎?huì)將state的變化整合,再一起處理,因此當(dāng)setState被調(diào)用的時(shí)候,state并不一定會(huì)立即變化。

這意味著在調(diào)用setState的時(shí)候你不能依賴當(dāng)前的state值——因?yàn)槟悴荒艽_保setState真正被調(diào)用的時(shí)候state究竟是什么。

解決方案就是給setState傳入一個(gè)方法,該方法接收上一次的state作為參數(shù)。

this.setState(prevState => ({ expanded: !prevState.expanded })

解構(gòu)props

  1. import React, { Component } from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { string, object } from 'prop-types' 
  4. import ExpandableForm from './ExpandableForm' 
  5. import './styles/ProfileContainer.css' 
  6. export default class ProfileContainer extends Component { 
  7.   state = { expanded: false } 
  8.   
  9.   static propTypes = { 
  10.     model: object.isRequired, 
  11.     title: string 
  12.   } 
  13.   
  14.   static defaultProps = { 
  15.     model: { 
  16.       id: 0 
  17.     }, 
  18.     title: 'Your Name' 
  19.   } 
  20.   handleSubmit = (e) => { 
  21.     e.preventDefault() 
  22.     this.props.model.save() 
  23.   } 
  24.    
  25.   handleNameChange = (e) => { 
  26.     this.props.model.changeName(e.target.value) 
  27.   } 
  28.    
  29.   handleExpand = (e) => { 
  30.     e.preventDefault() 
  31.     this.setState(prevState => ({ expanded: !prevState.expanded })) 
  32.   } 
  33.    
  34.   render() { 
  35.     const { 
  36.       model, 
  37.       title 
  38.     } = this.props 
  39.     return (  
  40.       <ExpandableForm  
  41.         onSubmit={this.handleSubmit}  
  42.         expanded={this.state.expanded}  
  43.         onExpand={this.handleExpand}> 
  44.         <div> 
  45.           <h1>{title}</h1> 
  46.           <input 
  47.             type="text" 
  48.             value={model.name
  49.             onChange={this.handleNameChange} 
  50.             placeholder="Your Name"/> 
  51.         </div> 
  52.       </ExpandableForm> 
  53.     ) 
  54.   } 
  55.  

對(duì)于有很多props的組件來說,應(yīng)當(dāng)像上述寫法一樣,將每個(gè)屬性解構(gòu)出來,且每個(gè)屬性單獨(dú)一行。

裝飾器(Decorators)

  1. @observer 
  2.  
  3. export default class ProfileContainer extends Component {  

如果你正在使用類似于mobx的狀態(tài)管理器,你可以按照上述方式描述你的組件。這種寫法與將組件作為參數(shù)傳遞給一個(gè)函數(shù)效果是一樣的。裝飾器(decorators)是一種非常靈活和易讀的定義組件功能的方式。我們使用mobx和mobx-models來結(jié)合裝飾器進(jìn)行使用。

如果你不想使用裝飾器,可以按照如下方式來做:

  1. class ProfileContainer extends Component { 
  2.  
  3. // Component code 
  4.  
  5.  
  6. export default observer(ProfileContainer)  

閉包

避免向子組件傳入閉包,如下:

  1. <input 
  2.             type="text" 
  3.             value={model.name
  4.             // onChange={(e) => { model.name = e.target.value }} 
  5.             // ^ 不要這樣寫,按如下寫法: 
  6.             onChange={this.handleChange} 
  7.             placeholder="Your Name"/>  

原因在于:每次父組件重新渲染時(shí),都會(huì)創(chuàng)建一個(gè)新的函數(shù),并傳給input。

如果這個(gè)input是個(gè)react組件的話,這會(huì)導(dǎo)致無論該組件的其他屬性是否變化,該組件都會(huì)重新render。

而且,采用將父組件的方法傳入的方式也會(huì)使得代碼更易讀,方便調(diào)試,同時(shí)也容易修改。

完整代碼如下:

  1. import React, { Component } from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { string, object } from 'prop-types' 
  4. // Separate local imports from dependencies 
  5. import ExpandableForm from './ExpandableForm' 
  6. import './styles/ProfileContainer.css' 
  7.  
  8. // Use decorators if needed 
  9. @observer 
  10. export default class ProfileContainer extends Component { 
  11.   state = { expanded: false } 
  12.   // Initialize state here (ES7) or in a constructor method (ES6) 
  13.   
  14.   // Declare propTypes as static properties as early as possible 
  15.   static propTypes = { 
  16.     model: object.isRequired, 
  17.     title: string 
  18.   } 
  19.  
  20.   // Default props below propTypes 
  21.   static defaultProps = { 
  22.     model: { 
  23.       id: 0 
  24.     }, 
  25.     title: 'Your Name' 
  26.   } 
  27.  
  28.   // Use fat arrow functions for methods to preserve context (this will thus be the component instance) 
  29.   handleSubmit = (e) => { 
  30.     e.preventDefault() 
  31.     this.props.model.save() 
  32.   } 
  33.    
  34.   handleNameChange = (e) => { 
  35.     this.props.model.name = e.target.value 
  36.   } 
  37.    
  38.   handleExpand = (e) => { 
  39.     e.preventDefault() 
  40.     this.setState(prevState => ({ expanded: !prevState.expanded })) 
  41.   } 
  42.  
  43.   render() { 
  44.     // Destructure props for readability 
  45.     const { 
  46.       model, 
  47.       title 
  48.     } = this.props 
  49.     return (  
  50.       <ExpandableForm  
  51.         onSubmit={this.handleSubmit}  
  52.         expanded={this.state.expanded}  
  53.         onExpand={this.handleExpand}> 
  54.         // Newline props if there are more than two 
  55.         <div> 
  56.           <h1>{title}</h1> 
  57.           <input 
  58.             type="text" 
  59.             value={model.name
  60.             // onChange={(e) => { model.name = e.target.value }} 
  61.             // Avoid creating new closures in the render method- use methods like below 
  62.             onChange={this.handleNameChange} 
  63.             placeholder="Your Name"/> 
  64.         </div> 
  65.         </ExpandableForm> 
  66.     ) 
  67.   } 
  68.  

函數(shù)組件(Functional Components)

這些組件沒有state和方法。它們是純凈的,非常容易定位問題,可以盡可能多的使用這些組件。

propTypes

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool 
  9. // Component declaration  

這里我們在組件聲明之前就定義了propTypes,非常直觀。我們可以這么做是因?yàn)閖s的函數(shù)名提升機(jī)制。

Destructuring Props and defaultProps(解構(gòu)props和defaultProps)

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool, 
  9.   onExpand: func.isRequired 
  10. function ExpandableForm(props) { 
  11.   const formStyle = props.expanded ? {height: 'auto'} : {height: 0} 
  12.   return ( 
  13.     <form style={formStyle} onSubmit={props.onSubmit}> 
  14.       {props.children} 
  15.       <button onClick={props.onExpand}>Expand</button> 
  16.     </form> 
  17.   ) 
  18.  

我們的組件是一個(gè)函數(shù),props作為函數(shù)的入?yún)⒈粋鬟f進(jìn)來。我們可以按照如下方式對(duì)組件進(jìn)行擴(kuò)展:

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4. import './styles/Form.css' 
  5. ExpandableForm.propTypes = { 
  6.   onSubmit: func.isRequired, 
  7.   expanded: bool, 
  8.   onExpand: func.isRequired 
  9. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  10.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
  11.   return ( 
  12.     <form style={formStyle} onSubmit={onSubmit}> 
  13.       {children} 
  14.       <button onClick={onExpand}>Expand</button> 
  15.     </form> 
  16.   ) 
  17.  

我們可以給參數(shù)設(shè)置默認(rèn)值,作為defaultProps。如果expanded是undefined,就將其設(shè)置為false。(這種設(shè)置默認(rèn)值的方式,對(duì)于對(duì)象類的入?yún)⒎浅S杏?,可以避免`can't read property XXXX of undefined的錯(cuò)誤)

不要使用es6箭頭函數(shù)的寫法:

  1. const ExpandableForm = ({ onExpand, expanded, children }) => { 

這種寫法中,函數(shù)實(shí)際是匿名函數(shù)。如果正確地使用了babel則不成問題,但是如果沒有,運(yùn)行時(shí)就會(huì)導(dǎo)致一些錯(cuò)誤,非常不方便調(diào)試。

另外,在Jest,一個(gè)react的測試庫,中使用匿名函數(shù)也會(huì)導(dǎo)致一些問題。由于使用匿名函數(shù)可能會(huì)出現(xiàn)一些潛在的問題,我們推薦使用function,而不是const。

Wrapping

在函數(shù)組件中不能使用裝飾器,我們可以將其作為入?yún)鹘oobserver函數(shù)

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool, 
  9.   onExpand: func.isRequired 
  10. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  11.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
  12.   return ( 
  13.     <form style={formStyle} onSubmit={onSubmit}> 
  14.       {children} 
  15.       <button onClick={onExpand}>Expand</button> 
  16.     </form> 
  17.   ) 
  18. export default observer(ExpandableForm)  

完整組件如下所示:

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4. // Separate local imports from dependencies 
  5. import './styles/Form.css' 
  6.  
  7. // Declare propTypes here, before the component (taking advantage of JS function hoisting) 
  8. // You want these to be as visible as possible 
  9. ExpandableForm.propTypes = { 
  10.   onSubmit: func.isRequired, 
  11.   expanded: bool, 
  12.   onExpand: func.isRequired 
  13.  
  14. // Destructure props like so, and use default arguments as a way of setting defaultProps 
  15. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  16.   const formStyle = expanded ? { height: 'auto' } : { height: 0 } 
  17.   return ( 
  18.     <form style={formStyle} onSubmit={onSubmit}> 
  19.       {children} 
  20.       <button onClick={onExpand}>Expand</button> 
  21.     </form> 
  22.   ) 
  23.  
  24. // Wrap the component instead of decorating it 
  25. export default observer(ExpandableForm)  

在JSX中使用條件判斷(Conditionals in JSX)

有時(shí)候我們需要在render中寫很多的判斷邏輯,以下這種寫法是我們應(yīng)該要避免的:

 

目前有一些庫來解決這個(gè)問題,但是我們沒有引入其他依賴,而是采用了如下方式來解決:

 

這里我們采用立即執(zhí)行函數(shù)的方式來解決問題,將if語句放到立即執(zhí)行函數(shù)中,返回任何你想返回的。需要注意的是,立即執(zhí)行函數(shù)會(huì)帶來一定的性能問題,但是對(duì)于代碼的可讀性來說,這個(gè)影響可以忽略。

同樣的,當(dāng)你只希望在某種情況下渲染時(shí),不要這么做:

  1.   isTrue 
  2.    ? <p>True!</p> 
  3.    : <none/> 
  4.  

而應(yīng)當(dāng)這么做:

  1.  
  2. isTrue && 
  3.  
  4. <p>True!</p> 
  5.  
  6.  

(全文完) 

責(zé)任編輯:龐桂玉 來源: segmentfault
相關(guān)推薦

2017-02-28 21:57:05

React組件

2022-05-13 08:48:50

React組件TypeScrip

2023-12-21 10:26:30

??Prettier

2019-07-22 10:42:11

React組件前端

2020-06-01 09:40:06

開發(fā)ReactTypeScript

2022-08-19 09:01:59

ReactTS類型

2020-06-03 16:50:24

TypeScriptReact前端

2019-07-20 23:30:48

開發(fā)技能代碼

2021-12-13 14:37:37

React組件前端

2021-12-07 08:16:34

React 前端 組件

2017-01-23 21:05:00

AndroidApp啟動(dòng)優(yōu)化

2016-08-23 10:50:50

WebJavascript緩存

2023-07-21 01:12:30

Reactfalse?變量

2017-04-06 09:56:52

大數(shù)據(jù)數(shù)據(jù)結(jié)轉(zhuǎn)技術(shù)架構(gòu)

2017-06-02 10:25:26

Java異常處理

2021-06-08 09:35:11

Cleaner ReaReact開發(fā)React代碼

2022-03-16 17:01:35

React18并發(fā)的React組件render

2017-01-12 13:26:38

大數(shù)據(jù)深度學(xué)習(xí)大數(shù)據(jù)技術(shù)

2017-05-25 10:58:08

HBase數(shù)據(jù)庫操作系統(tǒng)

2021-04-25 11:31:45

React代碼整潔代碼的實(shí)踐
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)