React 代碼共享最佳實(shí)踐方式
任何一個(gè)項(xiàng)目發(fā)展到一定復(fù)雜性的時(shí)候,必然會(huì)面臨邏輯復(fù)用的問(wèn)題。在React中實(shí)現(xiàn)邏輯復(fù)用通常有以下幾種方式:Mixin、高階組件(HOC)、修飾器(decorator)、Render Props、Hook。本文主要就以上幾種方式的優(yōu)缺點(diǎn)作分析,幫助開(kāi)發(fā)者針對(duì)業(yè)務(wù)場(chǎng)景作出更適合的方式。
Mixin—
這或許是剛從Vue轉(zhuǎn)向React的開(kāi)發(fā)者第一個(gè)能夠想到的方法。Mixin一直被廣泛用于各種面向?qū)ο蟮恼Z(yǔ)言中,其作用是為單繼承語(yǔ)言創(chuàng)造一種類(lèi)似多重繼承的效果。雖然現(xiàn)在React已將其放棄中,但Mixin的確曾是React實(shí)現(xiàn)代碼共享的一種設(shè)計(jì)模式。
廣義的 mixin 方法,就是用賦值的方式將 mixin 對(duì)象中的方法都掛載到原對(duì)象上,來(lái)實(shí)現(xiàn)對(duì)象的混入,類(lèi)似 ES6 中的 Object.assign()的作用。原理如下:
const mixin = function (obj, mixins) {
const newObj = obj
newObj.prototype = Object.create(obj.prototype)
for (let prop in mixins) {
// 遍歷mixins的屬性
if (mixins.hasOwnPrototype(prop)) {
// 判斷是否為mixin的自身屬性
newObj.prototype[prop] = mixins[prop]; // 賦值
}
}
return newObj
};
在 React 中使用 Mixin
假設(shè)在我們的項(xiàng)目中,多個(gè)組件都需要設(shè)置默認(rèn)的name屬性,使用mixin可以使我們不必在不同的組件里寫(xiě)多個(gè)同樣的getDefaultProps方法,我們可以定義一個(gè)mixin:
const DefaultNameMixin = {
getDefaultProps: function () {
return {
name: "Joy"
}
}
}
為了使用mixin,需要在組件中加入mixins屬性,然后把我們寫(xiě)好的mixin包裹成一個(gè)數(shù)組,將它作為mixins的屬性值:
const ComponentOne = React.createClass({
mixins: [DefaultNameMixin]
render: function () {
return <h2>Hello {this.props.name}</h2>
}
})
寫(xiě)好的mixin可以在其他組件里重復(fù)使用。
由于mixins屬性值是一個(gè)數(shù)組,意味著我們可以同一個(gè)組件里調(diào)用多個(gè)mixin。在上述例子中稍作更改得到:
const DefaultFriendMixin = {
getDefaultProps: function () {
return {
friend: "Yummy"
}
}
}
const ComponentOne = React.createClass({
mixins: [DefaultNameMixin, DefaultFriendMixin]
render: function () {
return (
<div>
<h2>Hello {this.props.name}</h2>
<h2>This is my friend {this.props.friend}</h2>
</div>
)
}
})
我們甚至可以在一個(gè)mixin里包含其他的mixin。
比如寫(xiě)一個(gè)新的mixin``DefaultProps包含以上的DefaultNameMixin和DefaultFriendMixin:
const DefaultPropsMixin = {
mixins: [DefaultNameMixin, DefaultFriendMixin]
}
const ComponentOne = React.createClass({
mixins: [DefaultPropsMixin]
render: function () {
return (
<div>
<h2>Hello {this.props.name}</h2>
<h2>This is my friend {this.props.friend}</h2>
</div>
)
}
})
至此,我們可以總結(jié)出mixin至少擁有以下優(yōu)勢(shì):
可以在多個(gè)組件里使用相同的 mixin;可以在同一個(gè)組件里使用多個(gè) mixin;可以在同一個(gè) mixin里嵌套多個(gè)mixin;
但是在不同場(chǎng)景下,優(yōu)勢(shì)也可能變成劣勢(shì):
破壞原有組件的封裝,可能需要去維護(hù)新的 state和props等狀態(tài);不同 mixin里的命名不可知,非常容易發(fā)生沖突;可能產(chǎn)生遞歸調(diào)用問(wèn)題,增加了項(xiàng)目復(fù)雜性和維護(hù)難度;
除此之外,mixin在狀態(tài)沖突、方法沖突、多個(gè)生命周期方法的調(diào)用順序等問(wèn)題擁有自己的處理邏輯。感興趣的同學(xué)可以參考一下以下文章:
React Mixin 的使用[1] Mixins Considered Harmful[2]
高階組件—
由于mixin存在上述缺陷,故React剝離了mixin,改用高階組件來(lái)取代它。
高階組件本質(zhì)上是一個(gè)函數(shù),它接受一個(gè)組件作為參數(shù),返回一個(gè)新的組件。
React官方在實(shí)現(xiàn)一些公共組件時(shí),也用到了高階組件,比如react-router中的withRouter,以及Redux中的connect。在這以withRouter為例。
默認(rèn)情況下,必須是經(jīng)過(guò)Route路由匹配渲染的組件才存在this.props、才擁有路由參數(shù)、才能使用函數(shù)式導(dǎo)航的寫(xiě)法執(zhí)行this.props.history.push('/next')跳轉(zhuǎn)到對(duì)應(yīng)路由的頁(yè)面。高階組件中的withRouter作用是將一個(gè)沒(méi)有被Route路由包裹的組件,包裹到Route里面,從而將react-router的三個(gè)對(duì)象history、location、match放入到該組件的props屬性里,因此能實(shí)現(xiàn)函數(shù)式導(dǎo)航跳轉(zhuǎn)。
withRouter的實(shí)現(xiàn)原理:
const withRouter = (Component) => {
const displayName = `withRouter(${Component.displayName || Component.name})`
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props
return (
<RouterContext.Consumer>
{context => {
invariant(
context,
`You should not use <${displayName} /> outside a <Router>`
);
return (
<Component
{...remainingProps}
{...context}
ref={wrappedComponentRef}
/>
)
}}
</RouterContext.Consumer>
)
}
使用代碼:
import React, { Component } from "react"
import { withRouter } from "react-router"
class TopHeader extends Component {
render() {
return (
<div>
導(dǎo)航欄
{/* 點(diǎn)擊跳轉(zhuǎn)login */}
<button onClick={this.exit}>退出</button>
</div>
)
}
exit = () => {
// 經(jīng)過(guò)withRouter高階函數(shù)包裹,就可以使用this.props進(jìn)行跳轉(zhuǎn)操作
this.props.history.push("/login")
}
}
// 使用withRouter包裹組件,返回history,location等
export default withRouter(TopHeader)
由于高階組件的本質(zhì)是獲取組件并且返回新組件的方法,所以理論上它也可以像mixin一樣實(shí)現(xiàn)多重嵌套。
例如:
寫(xiě)一個(gè)賦能唱歌的高階函數(shù)
import React, { Component } from 'react'
const widthSinging = WrappedComponent => {
return class HOC extends Component {
constructor () {
super(...arguments)
this.singing = this.singing.bind(this)
}
singing = () => {
console.log('i am singing!')
}
render() {
return <WrappedComponent />
}
}
}
寫(xiě)一個(gè)賦能跳舞的高階函數(shù)
import React, { Component } from 'react'
const widthDancing = WrappedComponent => {
return class HOC extends Component {
constructor () {
super(...arguments)
this.dancing = this.dancing.bind(this)
}
dancing = () => {
console.log('i am dancing!')
}
render() {
return <WrappedComponent />
}
}
}
使用以上高階組件
import React, { Component } from "react"
import { widthSing, widthDancing } from "hocs"
class Joy extends Component {
render() {
return <div>Joy</div>
}
}
// 給Joy賦能唱歌和跳舞的特長(zhǎng)
export default widthSinging(withDancing(Joy))
由上可見(jiàn),只需使用高階函數(shù)進(jìn)行簡(jiǎn)單的包裹,就可以把原本單純的 Joy 變成一個(gè)既能唱歌又能跳舞的夜店小王子了!
使用 HOC 的約定
在使用HOC的時(shí)候,有一些墨守成規(guī)的約定:
將不相關(guān)的 Props 傳遞給包裝組件(傳遞與其具體內(nèi)容無(wú)關(guān)的 props); 分步組合(避免不同形式的 HOC 串聯(lián)調(diào)用); 包含顯示的 displayName 方便調(diào)試(每個(gè) HOC 都應(yīng)該符合規(guī)則的顯示名稱); 不要在 render函數(shù)中使用高階組件(每次 render,高階都返回新組件,影響 diff 性能);靜態(tài)方法必須被拷貝(經(jīng)過(guò)高階返回的新組件,并不會(huì)包含原始組件的靜態(tài)方法); 避免使用 ref(ref 不會(huì)被傳遞);
HOC 的優(yōu)缺點(diǎn)
至此我們可以總結(jié)一下高階組件(HOC)的優(yōu)點(diǎn):
HOC是一個(gè)純函數(shù),便于使用和維護(hù);同樣由于 HOC是一個(gè)純函數(shù),支持傳入多個(gè)參數(shù),增強(qiáng)其適用范圍;HOC返回的是一個(gè)組件,可組合嵌套,靈活性強(qiáng);
當(dāng)然HOC也會(huì)存在一些問(wèn)題:
當(dāng)多個(gè) HOC嵌套使用時(shí),無(wú)法直接判斷子組件的props是從哪個(gè)HOC負(fù)責(zé)傳遞的;當(dāng)父子組件有同名 props,會(huì)導(dǎo)致父組件覆蓋子組件同名props的問(wèn)題,且react不會(huì)報(bào)錯(cuò),開(kāi)發(fā)者感知性低;每一個(gè) HOC都返回一個(gè)新組件,從而產(chǎn)生了很多無(wú)用組件,同時(shí)加深了組件層級(jí),不便于排查問(wèn)題;
修飾器和高階組件屬于同一模式,在此不展開(kāi)討論。
Render Props—
Render Props是一種非常靈活復(fù)用性非常高的模式,它可以把特定行為或功能封裝成一個(gè)組件,提供給其他組件使用讓其他組件擁有這樣的能力。
The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.
這是React官方對(duì)于Render Props的定義,翻譯成大白話即:“Render Props是實(shí)現(xiàn)React Components之間代碼共享的一種技術(shù),組件的props里邊包含有一個(gè)function類(lèi)型的屬性,組件可以調(diào)用該props屬性來(lái)實(shí)現(xiàn)組件內(nèi)部渲染邏輯”。
官方示例:
<DataProvider render={(data) => <h1>Hello {data.target}</h1>} />
如上,DataProvider組件擁有一個(gè)叫做render(也可以叫做其他名字)的props屬性,該屬性是一個(gè)函數(shù),并且這個(gè)函數(shù)返回了一個(gè)React Element,在組件內(nèi)部通過(guò)調(diào)用該函數(shù)來(lái)完成渲染,那么這個(gè)組件就用到了render props技術(shù)。
讀者或許會(huì)疑惑,“我們?yōu)槭裁葱枰{(diào)用props屬性來(lái)實(shí)現(xiàn)組件內(nèi)部渲染,而不直接在組件內(nèi)完成渲染”?借用React官方的答復(fù),render props并非每個(gè)React開(kāi)發(fā)者需要去掌握的技能,甚至你或許永遠(yuǎn)都不會(huì)用到這個(gè)方法,但它的存在的確為開(kāi)發(fā)者在思考組件代碼共享的問(wèn)題時(shí),提供了多一種選擇。
Render Props使用場(chǎng)景
我們?cè)陧?xiàng)目開(kāi)發(fā)中可能需要頻繁的用到彈窗,彈窗 UI 可以千變?nèi)f化,但是功能卻是類(lèi)似的,即打開(kāi)和關(guān)閉。以antd為例:
import { Modal, Button } from "antd"
class App extends React.Component {
state = { visible: false }
// 控制彈窗顯示隱藏
toggleModal = (visible) => {
this.setState({ visible })
};
handleOk = (e) => {
// 做點(diǎn)什么
this.setState({ visible: false })
}
render() {
const { visible } = this.state
return (
<div>
<Button onClick={this.toggleModal.bind(this, true)}>Open</Button>
<Modal
title="Basic Modal"
visible={visible}
onOk={this.handleOk}
onCancel={this.toggleModal.bind(this, false)}
>
<p>Some contents...</p>
</Modal>
</div>
)
}
}
以上是最簡(jiǎn)單的Model使用實(shí)例,即便是簡(jiǎn)單的使用,我們?nèi)孕枰P(guān)注它的顯示狀態(tài),實(shí)現(xiàn)它的切換方法。但是開(kāi)發(fā)者其實(shí)只想關(guān)注與業(yè)務(wù)邏輯相關(guān)的onOk,理想的使用方式應(yīng)該是這樣的:
<MyModal>
<Button>Open</Button>
<Modal title="Basic Modal" onOk={this.handleOk}>
<p>Some contents...</p>
</Modal>
</MyModal>
可以通過(guò)render props實(shí)現(xiàn)以上使用方式:
import { Modal, Button } from "antd"
class MyModal extends React.Component {
state = { on: false }
toggle = () => {
this.setState({
on: !this.state.on
})
}
renderButton = (props) => <Button {...props} onClick={this.toggle} />
renderModal = ({ onOK, ...rest }) => (
<Modal
{...rest}
visible={this.state.on}
onOk={() => {
onOK && onOK()
this.toggle()
}}
onCancel={this.toggle}
/>
)
render() {
return this.props.children({
Button: this.renderButton,
Modal: this.renderModal
})
}
}
這樣我們就完成了一個(gè)具備狀態(tài)和基礎(chǔ)功能的Modal,我們?cè)谄渌?yè)面使用該Modal時(shí),只需要關(guān)注特定的業(yè)務(wù)邏輯即可。
以上可以看出,render props是一個(gè)真正的React組件,而不是像HOC一樣只是一個(gè)可以返回組件的函數(shù),這也意味著使用render props不會(huì)像HOC一樣產(chǎn)生組件層級(jí)嵌套的問(wèn)題,也不用擔(dān)心props命名沖突產(chǎn)生的覆蓋問(wèn)題。
render props使用限制
在render props中應(yīng)該避免使用箭頭函數(shù),因?yàn)檫@會(huì)造成性能影響。
比如:
// 不好的示例
class MouseTracker extends React.Component {
render() {
return (
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}/>
)
}
}
這樣寫(xiě)是不好的,因?yàn)?code style="font-size: 14px;overflow-wrap: break-word;padding: 2px 4px;border-radius: 4px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);background-color: rgba(27, 31, 35, 0.05);font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace;word-break: break-all;">render方法是有可能多次渲染的,使用箭頭函數(shù),會(huì)導(dǎo)致每次渲染的時(shí)候,傳入render的值都會(huì)不一樣,而實(shí)際上并沒(méi)有差別,這樣會(huì)導(dǎo)致性能問(wèn)題。
所以更好的寫(xiě)法應(yīng)該是將傳入render里的函數(shù)定義為實(shí)例方法,這樣即便我們多次渲染,但是綁定的始終是同一個(gè)函數(shù)。
// 好的示例
class MouseTracker extends React.Component {
renderCat(mouse) {
return <Cat mouse={mouse} />
}
render() {
return (
<Mouse render={this.renderTheCat} />
)
}
}
render props的優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
props 命名可修改,不存在相互覆蓋; 清楚 props 來(lái)源; 不會(huì)出現(xiàn)組件多層嵌套; 缺點(diǎn)
寫(xiě)法繁瑣;
無(wú)法在
return語(yǔ)句外訪問(wèn)數(shù)據(jù);容易產(chǎn)生函數(shù)回調(diào)嵌套;
如下代碼:
const MyComponent = () => {
return (
<Mouse>
{({ x, y }) => (
<Page>
{({ x: pageX, y: pageY }) => (
<Connection>
{({ api }) => {
// yikes
}}
</Connection>
)}
</Page>
)}
</Mouse>
)
}
Hook—
React的核心是組件,因此,React一直致力于優(yōu)化和完善聲明組件的方式。從最早的類(lèi)組件,再到函數(shù)組件,各有優(yōu)缺點(diǎn)。類(lèi)組件可以給我們提供一個(gè)完整的生命周期和狀態(tài)(state),但是在寫(xiě)法上卻十分笨重,而函數(shù)組件雖然寫(xiě)法非常簡(jiǎn)潔輕便,但其限制是必須是純函數(shù),不能包含狀態(tài),也不支持生命周期,因此類(lèi)組件并不能取代函數(shù)組件。
而React團(tuán)隊(duì)覺(jué)得組件的最佳寫(xiě)法應(yīng)該是函數(shù),而不是類(lèi),由此產(chǎn)生了React Hooks。
React Hooks 的設(shè)計(jì)目的,就是加強(qiáng)版函數(shù)組件,完全不使用"類(lèi)",就能寫(xiě)出一個(gè)全功能的組件。
為什么說(shuō)類(lèi)組件“笨重”,借用React官方的例子說(shuō)明:
import React, { Component } from "react"
export default class Button extends Component {
constructor() {
super()
this.state = { buttonText: "Click me, please" }
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState(() => {
return { buttonText: "Thanks, been clicked!" }
})
}
render() {
const { buttonText } = this.state
return <button onClick={this.handleClick}>{buttonText}</button>
}
}
以上是一個(gè)簡(jiǎn)單的按鈕組件,包含最基礎(chǔ)的狀態(tài)和點(diǎn)擊方法,點(diǎn)擊按鈕后狀態(tài)發(fā)生改變。
本是很簡(jiǎn)單的功能組件,但是卻需要大量的代碼去實(shí)現(xiàn)。由于函數(shù)組件不包含狀態(tài),所以我們并不能用函數(shù)組件來(lái)聲明一個(gè)具備如上功能的組件。但是我們可以用Hook來(lái)實(shí)現(xiàn):
import React, { useState } from "react"
export default function Button() {
const [buttonText, setButtonText] = useState("Click me, please")
function handleClick() {
return setButtonText("Thanks, been clicked!")
}
return <button onClick={handleClick}>{buttonText}</button>
}
相較而言,Hook顯得更輕量,在貼近函數(shù)組件的同時(shí),保留了自己的狀態(tài)。
在上述例子中引入了第一個(gè)鉤子useState(),除此之外,React官方還提供了useEffect()、useContext()、useReducer()等鉤子。具體鉤子及其用法詳情請(qǐng)見(jiàn)官方[3]。
Hook的靈活之處還在于,除了官方提供的基礎(chǔ)鉤子之外,我們還可以利用這些基礎(chǔ)鉤子來(lái)封裝和自定義鉤子,從而實(shí)現(xiàn)更容易的代碼復(fù)用。
Hook 優(yōu)缺點(diǎn)
優(yōu)點(diǎn) 更容易復(fù)用代碼; 清爽的代碼風(fēng)格; 代碼量更少; 缺點(diǎn) 狀態(tài)不同步(函數(shù)獨(dú)立運(yùn)行,每個(gè)函數(shù)都有一份獨(dú)立的作用域) 需要更合理的使用 useEffect顆粒度小,對(duì)于復(fù)雜邏輯需要抽象出很多 hook
總結(jié)—
除了Mixin因?yàn)樽陨淼拿黠@缺陷而稍顯落后之外,對(duì)于高階組件、render props、react hook而言,并沒(méi)有哪種方式可稱為最佳方案,它們都是優(yōu)勢(shì)與劣勢(shì)并存的。哪怕是最為最熱門(mén)的react hook,雖然每一個(gè)hook看起來(lái)都是那么的簡(jiǎn)短和清爽,但是在實(shí)際業(yè)務(wù)中,通常都是一個(gè)業(yè)務(wù)功能對(duì)應(yīng)多個(gè)hook,這就意味著當(dāng)業(yè)務(wù)改變時(shí),需要去維護(hù)多個(gè)hook的變更,相對(duì)于維護(hù)一個(gè)class而言,心智負(fù)擔(dān)或許要增加許多。只有切合自身業(yè)務(wù)的方式,才是最佳方案。
參考資料
React Mixin 的使用: https://segmentfault.com/a/1190000003016446
[2]Mixins Considered Harmful: https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html
[3]官方: https://zh-hans.reactjs.org/docs/hooks-reference.html
[4]React Mixin 的使用: https://segmentfault.com/a/1190000003016446
[5]Mixins Considered Harmful: https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html
[6]Higher-Order Components: https://reactjs.org/docs/higher-order-components.html
[7]Render Props: https://reactjs.org/docs/render-props.html
[8]React 拾遺:Render Props 及其使用場(chǎng)景: https://www.imooc.com/article/39388
[9]Hook 簡(jiǎn)介: https://zh-hans.reactjs.org/docs/hooks-state.html
