<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          React 代碼共享最佳實踐方式

          共 18126字,需瀏覽 37分鐘

           ·

          2021-05-20 15:41

          任何一個項目發(fā)展到一定復雜性的時候,必然會面臨邏輯復用的問題。在React中實現(xiàn)邏輯復用通常有以下幾種方式:Mixin高階組件(HOC)修飾器(decorator)Render PropsHook。本文主要就以上幾種方式的優(yōu)缺點作分析,幫助開發(fā)者針對業(yè)務場景作出更適合的方式。

          Mixin

          這或許是剛從Vue轉(zhuǎn)向React的開發(fā)者第一個能夠想到的方法。Mixin一直被廣泛用于各種面向?qū)ο蟮恼Z言中,其作用是為單繼承語言創(chuàng)造一種類似多重繼承的效果。雖然現(xiàn)在React已將其放棄中,但Mixin的確曾是React實現(xiàn)代碼共享的一種設計模式。

          廣義的 mixin 方法,就是用賦值的方式將 mixin 對象中的方法都掛載到原對象上,來實現(xiàn)對象的混入,類似 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

          假設在我們的項目中,多個組件都需要設置默認的name屬性,使用mixin可以使我們不必在不同的組件里寫多個同樣的getDefaultProps方法,我們可以定義一個mixin

          const DefaultNameMixin = {
            getDefaultPropsfunction ({
              return {
                name"Joy"
              }
            }
          }

          為了使用mixin,需要在組件中加入mixins屬性,然后把我們寫好的mixin包裹成一個數(shù)組,將它作為mixins的屬性值:

          const ComponentOne = React.createClass({
            mixins: [DefaultNameMixin]
            renderfunction ({
              return <h2>Hello {this.props.name}</h2>
            }
          })

          寫好的mixin可以在其他組件里重復使用。

          由于mixins屬性值是一個數(shù)組,意味著我們可以同一個組件里調(diào)用多個mixin。在上述例子中稍作更改得到:

          const DefaultFriendMixin = {
            getDefaultPropsfunction ({
              return {
                friend"Yummy"
              }
            }
          }

          const ComponentOne = React.createClass({
            mixins: [DefaultNameMixin, DefaultFriendMixin]
            renderfunction ({
              return (
                <div>
                  <h2>Hello {this.props.name}</h2>
                  <h2>This is my friend {this.props.friend}</h2>
                </div>

              )
            }
          })

          我們甚至可以在一個mixin里包含其他的mixin

          比如寫一個新的mixin``DefaultProps包含以上的DefaultNameMixinDefaultFriendMixin

          const DefaultPropsMixin = {
            mixins: [DefaultNameMixin, DefaultFriendMixin]
          }

          const ComponentOne = React.createClass({
            mixins: [DefaultPropsMixin]
            renderfunction ({
              return (
                <div>
                  <h2>Hello {this.props.name}</h2>
                  <h2>This is my friend {this.props.friend}</h2>
                </div>

              )
            }
          })

          至此,我們可以總結(jié)出mixin至少擁有以下優(yōu)勢:

          • 可以在多個組件里使用相同的mixin
          • 可以在同一個組件里使用多個mixin
          • 可以在同一個mixin里嵌套多個mixin

          但是在不同場景下,優(yōu)勢也可能變成劣勢:

          • 破壞原有組件的封裝,可能需要去維護新的stateprops等狀態(tài)
          • 不同mixin里的命名不可知,非常容易發(fā)生沖突
          • 可能產(chǎn)生遞歸調(diào)用問題,增加了項目復雜性和維護難度

          除此之外,mixin在狀態(tài)沖突、方法沖突、多個生命周期方法的調(diào)用順序等問題擁有自己的處理邏輯。感興趣的同學可以參考一下以下文章:

          • React Mixin 的使用[1]
          • Mixins Considered Harmful[2]

          高階組件

          由于mixin存在上述缺陷,故React剝離了mixin,改用高階組件來取代它。

          高階組件本質(zhì)上是一個函數(shù),它接受一個組件作為參數(shù),返回一個新的組件

          React官方在實現(xiàn)一些公共組件時,也用到了高階組件,比如react-router中的withRouter,以及Redux中的connect。在這以withRouter為例。

          默認情況下,必須是經(jīng)過Route路由匹配渲染的組件才存在this.props、才擁有路由參數(shù)、才能使用函數(shù)式導航的寫法執(zhí)行this.props.history.push('/next')跳轉(zhuǎn)到對應路由的頁面。高階組件中的withRouter作用是將一個沒有被Route路由包裹的組件,包裹到Route里面,從而將react-router的三個對象historylocationmatch放入到該組件的props屬性里,因此能實現(xiàn)函數(shù)式導航跳轉(zhuǎn)

          withRouter的實現(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>
                  導航欄
                  {/* 點擊跳轉(zhuǎn)login */}
                  <button onClick={this.exit}>退出</button>
                </div>

              )
            }

            exit = () => {
              // 經(jīng)過withRouter高階函數(shù)包裹,就可以使用this.props進行跳轉(zhuǎn)操作
              this.props.history.push("/login")
            }
          }
          // 使用withRouter包裹組件,返回history,location等
          export default withRouter(TopHeader)

          由于高階組件的本質(zhì)是獲取組件并且返回新組件的方法,所以理論上它也可以像mixin一樣實現(xiàn)多重嵌套。

          例如:

          寫一個賦能唱歌的高階函數(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 />
            }
           }
          }

          寫一個賦能跳舞的高階函數(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賦能唱歌和跳舞的特長
          export default widthSinging(withDancing(Joy))

          由上可見,只需使用高階函數(shù)進行簡單的包裹,就可以把原本單純的 Joy 變成一個既能唱歌又能跳舞的夜店小王子了!

          使用 HOC 的約定

          在使用HOC的時候,有一些墨守成規(guī)的約定:

          • 將不相關的 Props 傳遞給包裝組件(傳遞與其具體內(nèi)容無關的 props);
          • 分步組合(避免不同形式的 HOC 串聯(lián)調(diào)用);
          • 包含顯示的 displayName 方便調(diào)試(每個 HOC 都應該符合規(guī)則的顯示名稱);
          • 不要在render函數(shù)中使用高階組件(每次 render,高階都返回新組件,影響 diff 性能);
          • 靜態(tài)方法必須被拷貝(經(jīng)過高階返回的新組件,并不會包含原始組件的靜態(tài)方法);
          • 避免使用 ref(ref 不會被傳遞);

          HOC 的優(yōu)缺點

          至此我們可以總結(jié)一下高階組件(HOC)的優(yōu)點:

          • HOC是一個純函數(shù),便于使用和維護;
          • 同樣由于HOC是一個純函數(shù),支持傳入多個參數(shù),增強其適用范圍;
          • HOC返回的是一個組件,可組合嵌套,靈活性強;

          當然HOC也會存在一些問題:

          • 當多個HOC嵌套使用時,無法直接判斷子組件的props是從哪個HOC負責傳遞的;
          • 當父子組件有同名props,會導致父組件覆蓋子組件同名props的問題,且react不會報錯,開發(fā)者感知性低;
          • 每一個HOC都返回一個新組件,從而產(chǎn)生了很多無用組件,同時加深了組件層級,不便于排查問題;

          修飾器高階組件屬于同一模式,在此不展開討論。

          Render Props

          Render Props是一種非常靈活復用性非常高的模式,它可以把特定行為或功能封裝成一個組件,提供給其他組件使用讓其他組件擁有這樣的能力

          The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

          這是React官方對于Render Props的定義,翻譯成大白話即:“Render Props是實現(xiàn)React Components之間代碼共享的一種技術,組件的props里邊包含有一個function類型的屬性,組件可以調(diào)用該props屬性來實現(xiàn)組件內(nèi)部渲染邏輯”。

          官方示例:

          <DataProvider render={(data) => <h1>Hello {data.target}</h1>} />

          如上,DataProvider組件擁有一個叫做render(也可以叫做其他名字)的props屬性,該屬性是一個函數(shù),并且這個函數(shù)返回了一個React Element,在組件內(nèi)部通過調(diào)用該函數(shù)來完成渲染,那么這個組件就用到了render props技術。

          讀者或許會疑惑,“我們?yōu)槭裁葱枰{(diào)用props屬性來實現(xiàn)組件內(nèi)部渲染,而不直接在組件內(nèi)完成渲染”?借用React官方的答復,render props并非每個React開發(fā)者需要去掌握的技能,甚至你或許永遠都不會用到這個方法,但它的存在的確為開發(fā)者在思考組件代碼共享的問題時,提供了多一種選擇。

          Render Props使用場景

          我們在項目開發(fā)中可能需要頻繁的用到彈窗,彈窗 UI 可以千變?nèi)f化,但是功能卻是類似的,即打開關閉。以antd為例:

          import { Modal, Button } from "antd"
          class App extends React.Component {
            state = { visiblefalse }

            // 控制彈窗顯示隱藏
            toggleModal = (visible) => {
              this.setState({ visible })
            };

            handleOk = (e) => {
              // 做點什么
              this.setState({ visiblefalse })
            }

            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>

              )
            }
          }

          以上是最簡單的Model使用實例,即便是簡單的使用,我們?nèi)孕枰P注它的顯示狀態(tài),實現(xiàn)它的切換方法。但是開發(fā)者其實只想關注與業(yè)務邏輯相關的onOk,理想的使用方式應該是這樣的:

          <MyModal>
            <Button>Open</Button>
            <Modal title="Basic Modal" onOk={this.handleOk}>
              <p>Some contents...</p>
            </Modal>

          </MyModal>

          可以通過render props實現(xiàn)以上使用方式:

          import { Modal, Button } from "antd"
          class MyModal extends React.Component {
            state = { onfalse }

            toggle = () => {
              this.setState({
                on: !this.state.on
              })
            }

            renderButton = (props) => <Button {...propsonClick={this.toggle} />

            renderModal = ({ onOK, ...rest }) => (
              <Modal
                {...rest}
                visible={this.state.on}
                onOk={() =>
           {
                  onOK && onOK()
                  this.toggle()
                }}
                onCancel={this.toggle}
              />

            )

            render() {
              return this.props.children({
                Buttonthis.renderButton,
                Modalthis.renderModal
              })
            }
          }

          這樣我們就完成了一個具備狀態(tài)和基礎功能的Modal,我們在其他頁面使用該Modal時,只需要關注特定的業(yè)務邏輯即可。

          以上可以看出,render props是一個真正的React組件,而不是像HOC一樣只是一個可以返回組件的函數(shù),這也意味著使用render props不會像HOC一樣產(chǎn)生組件層級嵌套的問題,也不用擔心props命名沖突產(chǎn)生的覆蓋問題。

          render props使用限制

          render props中應該避免使用箭頭函數(shù),因為這會造成性能影響。

          比如:

          // 不好的示例
          class MouseTracker extends React.Component {
            render() {
              return (
                <Mouse render={mouse => (
                  <Cat mouse={mouse} />
                )}/>

              )
            }
          }

          這樣寫是不好的,因為render方法是有可能多次渲染的,使用箭頭函數(shù),會導致每次渲染的時候,傳入render的值都會不一樣,而實際上并沒有差別,這樣會導致性能問題。

          所以更好的寫法應該是將傳入render里的函數(shù)定義為實例方法,這樣即便我們多次渲染,但是綁定的始終是同一個函數(shù)。

          // 好的示例
          class MouseTracker extends React.Component {
            renderCat(mouse) {
             return <Cat mouse={mouse} />
            }

            render() {
              return (
              <Mouse render={this.renderTheCat} />
              )
            }
          }

          render props的優(yōu)缺點

          • 優(yōu)點

            • props 命名可修改,不存在相互覆蓋;
            • 清楚 props 來源;
            • 不會出現(xiàn)組件多層嵌套;
          • 缺點

            • 寫法繁瑣;

            • 無法在return語句外訪問數(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)化和完善聲明組件的方式。從最早的類組件,再到函數(shù)組件,各有優(yōu)缺點。類組件可以給我們提供一個完整的生命周期和狀態(tài)(state),但是在寫法上卻十分笨重,而函數(shù)組件雖然寫法非常簡潔輕便,但其限制是必須是純函數(shù),不能包含狀態(tài),也不支持生命周期,因此類組件并不能取代函數(shù)組件

          React團隊覺得組件的最佳寫法應該是函數(shù),而不是類,由此產(chǎn)生了React Hooks

          React Hooks 的設計目的,就是加強版函數(shù)組件,完全不使用"類",就能寫出一個全功能的組件

          為什么說類組件“笨重”,借用React官方的例子說明:

          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>
            }
          }

          以上是一個簡單的按鈕組件,包含最基礎的狀態(tài)和點擊方法,點擊按鈕后狀態(tài)發(fā)生改變。

          本是很簡單的功能組件,但是卻需要大量的代碼去實現(xiàn)。由于函數(shù)組件不包含狀態(tài),所以我們并不能用函數(shù)組件來聲明一個具備如上功能的組件。但是我們可以用Hook來實現(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ù)組件的同時,保留了自己的狀態(tài)。

          在上述例子中引入了第一個鉤子useState(),除此之外,React官方還提供了useEffect()useContext()useReducer()等鉤子。具體鉤子及其用法詳情請見官方[3]

          Hook的靈活之處還在于,除了官方提供的基礎鉤子之外,我們還可以利用這些基礎鉤子來封裝和自定義鉤子,從而實現(xiàn)更容易的代碼復用。

          Hook 優(yōu)缺點

          • 優(yōu)點
            • 更容易復用代碼;
            • 清爽的代碼風格;
            • 代碼量更少;
          • 缺點
            • 狀態(tài)不同步(函數(shù)獨立運行,每個函數(shù)都有一份獨立的作用域)
            • 需要更合理的使用useEffect
            • 顆粒度小,對于復雜邏輯需要抽象出很多hook

          總結(jié)

          除了Mixin因為自身的明顯缺陷而稍顯落后之外,對于高階組件render propsreact hook而言,并沒有哪種方式可稱為最佳方案,它們都是優(yōu)勢與劣勢并存的。哪怕是最為最熱門的react hook,雖然每一個hook看起來都是那么的簡短和清爽,但是在實際業(yè)務中,通常都是一個業(yè)務功能對應多個hook,這就意味著當業(yè)務改變時,需要去維護多個hook的變更,相對于維護一個class而言,心智負擔或許要增加許多。只有切合自身業(yè)務的方式,才是最佳方案


          參考資料

          [1]

          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 及其使用場景: https://www.imooc.com/article/39388

          [9]

          Hook 簡介: https://zh-hans.reactjs.org/docs/hooks-state.html


          瀏覽 45
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美一级a一级a爱片免费 | 亚洲视屏| 操逼黄色片 | 日本一级一片免费播放 | 亚洲欧洲AⅤ |