1

在我的項目中,我試圖擺脫所有mixin並將其替換爲HOC。目前我使用ES5卡住了。將ES5 Mixins轉換爲高階組件

export default React.createClass({ 
    mixins: [SomeAsyncMixin], 
    data: { 
    item1: { 
     params: ({params, query}) => { 
     params: ({params, query}) => { 
      if (!query.p) { 
       return null; 
      } 
      const status = someTernaryResult 
      return { 
       groups: query.groups, 
       status, 
       subject: params.subject, 
      }; 
     }, 
     promise: query => query && query.subject && api(makeUrl(`/some/endpoint`, query)) 
     }, 

    item2: { 
     params: ({params, query}) => { 
      //same as before 
     }, 
     promise: ({subject, query}) => 
      // same as before 
    } 

    render() { 
     // some stuff 

     return(
     // some jsx 
    ); 
    } 
} 

裏面混入的,它有一個componentWillMount和運行一個update功能將通過在data每個鍵循環和更新道具/狀態componentWillUpdate

在React的docs有關去除mixin,它們的mixin保存數據,而不是組件。

我的項目中有很多組件有一個data對象,並使用這個mixin來更新他們的道具/狀態。如何製作一個可重用組件來處理這個數據對象?

另外,我怎樣才能從組件內訪問這個數據對象?組件this.data爲空。 mixin this.data的內部是組件內部的數據對象。爲什麼?

回答

0

您的高階組件和mixin看起來非常相似。主要區別在於如何共享/傳遞data,道具和狀態。在mixin的情況下,你正在用mixin的行爲改變你的組件的定義,所以狀態和道具都在最終的組件中。

在更高順序的組件情況下,您正在創建一個新的組件來環繞其他組件。因此,共享狀態/行爲完全包含在包裝組件中,並且需要在包裝組件中使用的任何數據都可以通過道具傳遞。

所以從你在你的例子是什麼,你的高階組件會像

const someAsync = (data) => (WrappedComponent) => { 
    class SomeAsyncComponent extends React.Component { 
     constructor(...args) { 
      super(...args) 

      this.state = { 
       ... 
      } 
     } 

     componentWillMount() { 
      // Make use of data, props, state, etc 
      ... 
     } 

     componentWillUpdate() { 
      ... 
     } 

     render() { 
      // May filter out some props/state, depending on what is needed 
      // Can also pass data through if the WrappedComponent needs it. 
      return (
       <WrappedComponent 
        { ...this.props } 
        { ...this.state } 
       /> 
      ) 
     } 
    } 

    return SomeAsyncComponent 
} 

然後你對它的使用

export default someAsync(dataConfig)(WrappedComponent)