裝飾器(Decorator)在React中的應用

一直沒理解Decorator的作用,但最近在很多框架和庫中看到它的身影,尤其是React和Redux,還有mobx中,所以專門查了一下資料,記錄一下。

修飾器(Decorator)是一個函數,用來修改類的行為。不是很理解這種抽象概念,還是看代碼講解實際些。

//定義一個函數,也就是定義一個Decorator,target參數就是傳進來的Class。
//這里是為類添加了一個靜態屬性
function testable(target) {
  target.isTestable = true;
}

//在Decorator后面跟著Class,Decorator是函數的話,怎么不是testable(MyTestableClass)這樣寫呢?
//我只能這樣理解:因為語法就這樣,只要Decorator后面是Class,默認就已經把Class當成參數隱形傳進Decorator了。
@testable
class MyTestableClass {}

console.log(MyTestableClass.isTestable) // true

但上面這樣只傳了一個Class作為參數不夠靈活怎么辦?
我們可以在外層套一個函數,只要最后返回的是一個Decorator即可,管你套多少個函數傳多少個參數都無所謂。

function testable(isTestable) {
  return function(target) {
    target.isTestable = isTestable;
  }
}

//注意這里,隱形傳入了Class,語法類似于testable(true)(MyTestableClass)
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true

@testable(false)
class MyClass {}
MyClass.isTestable // false

下面是修改類的prototype對象

function testable(target) {
  target.prototype.isTestable = true;
}

@testable
class MyTestableClass {}

let obj = new MyTestableClass();
obj.isTestable // true

概念大概理解了,修飾器不僅可以修飾類,還可以修飾類的屬性

//假如修飾類的屬性則傳入三個參數,對應Object.defineProperty()里三個參數,具體不細說
//target為目標對象,對應為Class的實例
//name為所要修飾的屬性名,這里就是修飾器緊跟其后的name屬性
//descriptor為該屬性的描述對象
//這里的Decorator作用是使name屬性不可寫,并返回修改后的descriptor
function readonly(target, name, descriptor){
  descriptor.writable = false;
  return descriptor;
}

class Person {
  @readonly
  name() { return `${this.first} ${this.last}` }
}

關于Object.defineProperty()可以看文章學習Object.defineProperty

再看一個復雜的例子

//定義一個Class并在其add上使用了修飾器
class Math {
  @log
  add(a, b) {
    return a + b;
  }
}

//定義一個修飾器
function log(target, name, descriptor) {
  //這里是緩存舊的方法,也就是上面那個add()原始方法
  var oldValue = descriptor.value;

  //這里修改了方法,使其作用變成一個打印函數
  //最后依舊返回舊的方法,真是巧妙
  descriptor.value = function() {
    console.log(`Calling "${name}" with`, arguments);
    return oldValue.apply(null, arguments);
  };

  return descriptor;
}

const math = new Math();
math.add(2, 4);

看完上面的代碼之后也大概了解裝飾器是什么作用了,下面是看看怎么在React里使用。
我們都知道組件也是Class,但寫React的時候怎么不見 new 語法?因為你應用組件的時候React隱性幫你實例化了。
這里展示一個例子用于切換React路由時,動態更改title屬性的裝飾器

//假如有這么一個頁面組件,用于顯示用戶資料的,當從Home組件進去到這個組件時
//希望title從“Home Page”變成“Profile Page”
//注意這里隱形傳入了組件,語法類似setTitle('Profile Page')(Profile)
@setTitle('Profile Page')
class Profile extends React.Component {
    //....
}

//開始定義裝飾器
//看到兩個箭頭函數感覺懵逼了,轉化一個也就是一個函數里返回一個函數再返回一個組件包裹器而已
//title參數對應上面的“Profile Page”字符串
//WrappedComponent參數對應上面的Profile組件
//然后在組件加載完修改了title,在返回一個新組件,是不是很像高階組件呢
const setTitle = (title) => (WrappedComponent) => {
   return class extends React.Component {
      componentDidMount() {
          document.title = title
      }
      render() {
         return <WrappedComponent {...this.props} />
      }
   }
}

最后看看現在react-redux中怎么應用裝飾器的

//定義一個組件
class Home extends React.Component {
    //....
}

//以往從狀態樹取出對應的數據,讓后通過props傳給組件使用通過react-redux自帶的connect()方法
export default connect(state => ({todos: state.todos}))(Home);

//使用裝飾器的話就變成這樣,好像沒那么復雜
@connect(state => ({ todos: state.todos }))
class Home extends React.Component {
    //....
}

參考文檔:
http://es6.ruanyifeng.com/#docs/decorator
https://survivejs.com/react/appendices/understanding-decorators/
https://medium.com/@gigobyte/enhancing-react-components-with-decorators-441320e8606a
http://stackoverflow.com/questions/36553814/what-is-the-use-of-connect-decorator-in-react-redux

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容