翻譯:劉小夕javascript
原文連接:dmitripavlutin.com/7-architect…html
原文的篇幅很是長,不過內容太過於吸引我,仍是忍不住要翻譯出來。此篇文章對編寫可重用和可維護的React組件很是有幫助。但由於篇幅實在太長,我不得不進行了分割,本篇文章重點闡述 SRP
,即單一職責原則。java
更多文章可戳: github.com/YvetteLau/B…react
————————————我是一條分割線————————————ios
我喜歡React組件式開發方式。你能夠將複雜的用戶界面分割爲一個個組件,利用組件的可重用性和抽象的DOM操做。git
基於組件的開發是高效的:一個複雜的系統是由專門的、易於管理的組件構建的。然而,只有設計良好的組件才能確保組合和複用的好處。github
儘管應用程序很複雜,但爲了知足最後期限和意外變化的需求,你必須不斷地走在架構正確性的細線上。你必須將組件分離爲專一於單個任務,並通過良好測試。axios
不幸的是,遵循錯誤的路徑老是更加容易:編寫具備許多職責的大型組件、緊密耦合組件、忘記單元測試。這些增長了技術債務,使得修改現有功能或建立新功能變得愈來愈困難。api
編寫React應用程序時,我常常問本身:數組
幸運的是,可靠的組件具備共同的特性。讓咱們來研究這7個有用的標準(本文只闡述 SRP
,剩餘準則正在途中),並將其詳細到案例研究中。
當一個組件只有一個改變的緣由時,它有一個單一的職責。
編寫React組件時要考慮的基本準則是單一職責原則。單一職責原則(縮寫:SRP
)要求組件有一個且只有一個變動的緣由。
組件的職責能夠是呈現列表,或者顯示日期選擇器,或者發出 HTTP
請求,或者繪製圖表,或者延遲加載圖像等。你的組件應該只選擇一個職責並實現它。當你修改組件實現其職責的方式(例如,更改渲染的列表的數量限制),它有一個更改的緣由。
爲何只有一個理由能夠改變很重要?由於這樣組件的修改隔離而且受控。單一職責原則制了組件的大小,使其集中在一件事情上。集中在一件事情上的組件便於編碼、修改、重用和測試。
下面咱們來舉幾個例子
實例1:一個組件獲取遠程數據,相應地,當獲取邏輯更改時,它有一個更改的緣由。
發生變化的緣由是:
示例2:表組件將數據數組映射到行組件列表,所以在映射邏輯更改時有一個緣由須要更改。
發生變化的緣由是:
你的組件有不少職責嗎?若是答案是「是」,則按每一個單獨的職責將組件分紅若干塊。
若是您發現SRP有點模糊,請閱讀本文。 在項目早期階段編寫的單元將常常更改,直到達到發佈階段。這些更改一般要求組件在隔離狀態下易於修改:這也是 SRP 的目標。
當一個組件有多個職責時,就會發生一個常見的問題。乍一看,這種作法彷佛是無害的,而且工做量較少:
props
和 callbacks
這種幼稚的結構在開始時很容易編碼。可是隨着應用程序的增長和變得複雜,在之後的修改中會出現困難。同時實現多個職責的組件有許多更改的緣由。如今出現的主要問題是:出於某種緣由更改組件會無心中影響同一組件實現的其它職責。
不要關閉電燈開關,由於它一樣做用於電梯。
這種設計很脆弱。意外的反作用是很難預測和控制的。
例如,<ChartAndForm>
同時有兩個職責,繪製圖表,並處理爲該圖表提供數據的表單。<ChartandForm>
就會有兩個更改緣由:繪製圖表和處理表單。
當你更改表單字段(例如,將 <input>
修改成 <select>
時,你無心中中斷圖表的渲染。此外,圖表實現是不可重用的,由於它與表單細節耦合在一塊兒。
解決多重責任問題須要將 <ChartAndForm>
分割爲兩個組件:<Chart>
和<Form>
。每一個組件只有一個職責:繪製圖表或處理表單。組件之間的通訊是經過props
實現。
多重責任問題的最壞狀況是所謂的上帝組件(上帝對象的類比)。上帝組件傾向於瞭解並作全部事情。你可能會看到它名爲 <Application>
、<Manager>
、<Bigcontainer>
或 <Page>
,代碼超過500行。
在組合的幫助下使其符合SRP,從而分解上帝組件。(組合(composition)是一種經過將各組件聯合在一塊兒以建立更大組件的方式。組合是 React 的核心。)
設想一個組件向一個專門的服務器發出 HTTP
請求,以獲取當前天氣。成功獲取數據時,該組件使用響應來展現天氣信息:
import axios from 'axios'; // 問題: 一個組件有多個職責 class Weather extends Component { constructor(props) { super(props); this.state = { temperature: 'N/A', windSpeed: 'N/A' }; } render() { const { temperature, windSpeed } = this.state; return ( <div className="weather"> <div>Temperature: {temperature}°C</div> <div>Wind: {windSpeed}km/h</div> </div> ); } componentDidMount() { axios.get('http://weather.com/api').then(function (response) { const { current } = response.data; this.setState({ temperature: current.temperature, windSpeed: current.windSpeed }) }); } } 複製代碼
在處理相似的狀況時,問問本身:是否必須將組件拆分爲更小的組件?經過肯定組件可能會如何根據其職責進行更改,能夠最好地回答這個問題。
這個天氣組件有兩個改變緣由:
componentDidMount()
中的 fetch
邏輯:服務器URL或響應格式可能會改變。
render()
中的天氣展現:組件顯示天氣的方式能夠屢次更改。
解決方案是將 <Weather>
分爲兩個組件:每一個組件只有一個職責。命名爲 <WeatherFetch>
和 <WeatherInfo>
。
<WeatherFetch>
組件負責獲取天氣、提取響應數據並將其保存到 state
中。它改變緣由只有一個就是獲取數據邏輯改變。
import axios from 'axios'; // 解決措施: 組件只有一個職責就是請求數據 class WeatherFetch extends Component { constructor(props) { super(props); this.state = { temperature: 'N/A', windSpeed: 'N/A' }; } render() { const { temperature, windSpeed } = this.state; return ( <WeatherInfo temperature={temperature} windSpeed={windSpeed} /> ); } componentDidMount() { axios.get('http://weather.com/api').then(function (response) { const { current } = response.data; this.setState({ temperature: current.temperature, windSpeed: current.windSpeed }); }); } } 複製代碼
這種結構有什麼好處?
例如,你想要使用 async/await
語法來替代 promise
去服務器獲取響應。更改緣由:修改獲取邏輯
// 改變緣由: 使用 async/await 語法 class WeatherFetch extends Component { // ..... // async componentDidMount() { const response = await axios.get('http://weather.com/api'); const { current } = response.data; this.setState({ temperature: current.temperature, windSpeed: current.windSpeed }); } } 複製代碼
由於 <WeatherFetch>
只有一個更改緣由:修改 fetch
邏輯,因此對該組件的任何修改都是隔離的。使用 async/await
不會直接影響天氣的顯示。
<WeatherFetch>
渲染 <WeatherInfo>
。後者只負責顯示天氣,改變緣由只多是視覺顯示改變。
// 解決方案: 組件只有一個職責,就是顯示天氣 function WeatherInfo({ temperature, windSpeed }) { return ( <div className="weather"> <div>Temperature: {temperature}°C</div> <div>Wind: {windSpeed} km/h</div> </div> ); } 複製代碼
讓咱們更改<WeatherInfo>
,如不顯示 「wind:0 km/h」
而是顯示 「wind:calm」
。這就是天氣視覺顯示發生變化的緣由:
// 改變緣由: 無風時的顯示 function WeatherInfo({ temperature, windSpeed }) { const windInfo = windSpeed === 0 ? 'calm' : `${windSpeed} km/h`; return ( <div className="weather"> <div>Temperature: {temperature}°C</div> <div>Wind: {windInfo}</div> </div> ); } 複製代碼
一樣,對 <WeatherInfo>
的修改是隔離的,不會影響 <WeatherFetch>
組件。
<WeatherFetch>
和 <WeatherInfo>
有各自的職責。一種組件的變化對另外一種組件的影響很小。這就是單一職責原則的做用:修改隔離,對系統的其餘組件產生影響很輕微而且可預測。
按職責使用分塊組件的組合並不老是有助於遵循單一責任原則。另一種有效實踐是高階組件(縮寫爲 HOC
)
高階組件是一個接受一個組件並返回一個新組件的函數。
HOC
的一個常見用法是爲封裝的組件增長新屬性或修改現有的屬性值。這種技術稱爲屬性代理:
function withNewFunctionality(WrappedComponent) { return class NewFunctionality extends Component { render() { const newProp = 'Value'; const propsProxy = { ...this.props, // 修改現有屬性: ownProp: this.props.ownProp + ' was modified', // 增長新屬性: newProp }; return <WrappedComponent {...propsProxy} />; } } } const MyNewComponent = withNewFunctionality(MyComponent); 複製代碼
你還能夠經過控制輸入組件的渲染過程從而控制渲染結果。這種 HOC
技術被稱爲渲染劫持:
function withModifiedChildren(WrappedComponent) {
return class ModifiedChildren extends WrappedComponent {
render() {
const rootElement = super.render();
const newChildren = [
...rootElement.props.children,
// 插入一個元素
<div>New child</div>
];
return cloneElement(
rootElement,
rootElement.props,
newChildren
);
}
}
}
const MyNewComponent = withModifiedChildren(MyComponent);
複製代碼
若是您想深刻了解HOCS實踐,我建議您閱讀「深刻響應高階組件」。
讓咱們經過一個例子來看看HOC的屬性代理技術如何幫助分離職責。
組件 <PersistentForm>
由 input
輸入框和按鈕 save to storage
組成。更改輸入值後,點擊 save to storage
按鈕將其寫入到 localStorage
中。
複製代碼
input
的狀態在 handlechange(event)
方法中更新。點擊按鈕,值將保存到本地存儲,在 handleclick()
中處理:
class PersistentForm extends Component { constructor(props) { super(props); this.state = { inputValue: localStorage.getItem('inputValue') }; this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); } render() { const { inputValue } = this.state; return ( <div className="persistent-form"> <input type="text" value={inputValue} onChange={this.handleChange} /> <button onClick={this.handleClick}>Save to storage</button> </div> ); } handleChange(event) { this.setState({ inputValue: event.target.value }); } handleClick() { localStorage.setItem('inputValue', this.state.inputValue); } } 複製代碼
遺憾的是: <PersistentForm>
有2個職責:管理表單字段;將輸入只保存中 localStorage
。
讓咱們重構一下 <PersistentForm>
組件,使其只有一個職責:展現表單字段和附加的事件處理程序。它不該該知道如何直接使用存儲:
class PersistentForm extends Component { constructor(props) { super(props); this.state = { inputValue: props.initialValue }; this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); } render() { const { inputValue } = this.state; return ( <div className="persistent-form"> <input type="text" value={inputValue} onChange={this.handleChange} /> <button onClick={this.handleClick}>Save to storage</button> </div> ); } handleChange(event) { this.setState({ inputValue: event.target.value }); } handleClick() { this.props.saveValue(this.state.inputValue); } } 複製代碼
組件從屬性初始值接收存儲的輸入值,並使用屬性函數 saveValue(newValue)
來保存輸入值。這些props
由使用屬性代理技術的 withpersistence()
HOC提供。
如今 <PersistentForm>
符合 SRP
。更改的惟一緣由是修改表單字段。
查詢和保存到本地存儲的職責由 withPersistence()
HOC承擔:
function withPersistence(storageKey, storage) { return function (WrappedComponent) { return class PersistentComponent extends Component { constructor(props) { super(props); this.state = { initialValue: storage.getItem(storageKey) }; } render() { return ( <WrappedComponent initialValue={this.state.initialValue} saveValue={this.saveValue} {...this.props} /> ); } saveValue(value) { storage.setItem(storageKey, value); } } } } 複製代碼
withPersistence()
是一個 HOC
,其職責是持久的。它不知道有關表單域的任何詳細信息。它只聚焦一個工做:爲傳入的組件提供 initialValue
字符串和 saveValue()
函數。
將 <PersistentForm>
和 withpersistence()
一塊兒使用能夠建立一個新組件<LocalStoragePersistentForm>
。它與本地存儲相連,能夠在應用程序中使用:
const LocalStoragePersistentForm = withPersistence('key', localStorage)(PersistentForm); const instance = <LocalStoragePersistentForm />; 複製代碼
只要 <PersistentForm>
正確使用 initialValue
和 saveValue()
屬性,對該組件的任何修改都不能破壞 withPersistence()
保存到存儲的邏輯。
反之亦然:只要 withPersistence()
提供正確的 initialValue
和 saveValue()
,對 HOC
的任何修改都不能破壞處理表單字段的方式。
SRP的效率再次顯現出來:修改隔離,從而減小對系統其餘部分的影響。
此外,代碼的可重用性也會增長。你能夠將任何其餘表單 <MyOtherForm>
鏈接到本地存儲:
const LocalStorageMyOtherForm = withPersistence('key', localStorage)(MyOtherForm); const instance = <LocalStorageMyOtherForm />; 複製代碼
你能夠輕鬆地將存儲類型更改成 session storage
:
const SessionStoragePersistentForm = withPersistence('key', sessionStorage)(PersistentForm); const instance = <SessionStoragePersistentForm />; 複製代碼
初始版本 <PersistentForm>
沒有隔離修改和可重用性好處,由於它錯誤地具備多個職責。
在很差分塊組合的狀況下,屬性代理和渲染劫持的 HOC
技術可使得組件只有一個職責。
謝謝各位小夥伴願意花費寶貴的時間閱讀本文,若是本文給了您一點幫助或者是啓發,請不要吝嗇你的贊和Star,您的確定是我前進的最大動力。 github.com/YvetteLau/B…