2017-08-03 41 views
1

我的反應網絡應用程序有一個頁面組件。頁面組件爲子組件執行異步調用。現在我必須在每一頁上都這樣反應 - 在每個組件上加載組件

export default class Page extends React.Component { 

constructor(props) { 
    super(props); 

    this.state = { 
     loading: true 
    } 
} 


componentWillMount = async() => { 
    // ... do calls 

    this.setState({ 
     loading: false 
    }) 
} 


render() { 
    if (this.state.loading) { 
     return <Loading/> 
    } else { 
     return (
      // Some other components that needs the information from the calls 
     ) 
    } 

} 
} 

有沒有辦法減少樣板?我正在考慮高級組件的反應。我想可能是一個組件,它將獲得需要創建的調用的函數以及在該函數之後呈現的組件。

const loader = (calls) => (WrappedComponent) => { 
    return class Loader extends React.Component { 

     constructor (props) { 
      super(props); 
      this.state = { 
       loading: true 
      } 
     } 

     componentWillMount =() => { 
      // execute calls function 
     }; 

     render() { 
      return this.state.loading ? <Loading/> : <WrappedComponent {... this.props }/> 
     } 
    } 

}; 

export default loader; 

但我還沒有想出一種方法將調用函數傳遞給加載函數。

回答

1

當然,你可以使用HOC做到這一點。

比方說,你的功能是沿

const yourFunction =() => { 
    return 'A value'; 
} 

線的東西。然後你可以簡單地把它傳遞給你的HOC作爲第二個參數:

const loader = (WrappedComponent, someFunction) => { 
    return class Loader extends React.Component { 

     constructor (props) { 
      super(props); 
      this.state = { 
       loading: true, 
       value: '', 
      } 
     } 

     componentWillMount =() => { 
      // execute the function you passed it 
      this.setState({value: yourFunction()}); 
     }; 

     render() { 
      const { loading, value } = this.state; 
      return loading ? <Loading/> : <WrappedComponent value={value} /> 
     } 
    } 

}; 

然後用它包住組件:

const EnhancedComponent = Loader(WrappedComponent, yourFunction); 

或者,您可以將HOC包裹在另一個HOC中,以傳遞像tha t ..

+0

謝謝,我會試試看。沒有想到一個HOC是如此簡單。 – oscarteg