2017-08-16 79 views
0

我有以下的代碼工作完全,但它的一個部分(_FetchJSON)是一個自定義HOC之外的重構使用recompose()進行異步的示例?

(現場演示@https://codepen.io/dakom/pen/zdpPWV?editors=0010

const LoadingView =() => <div>Please wait...</div>; 
const ReadyView = ({ image }) => <div> Got it! <img src={image} /> </div>;       

const Page = compose(
    _FetchJson, 
    branch(({ jsonData }) => !jsonData, renderComponent(LoadingView)), 
    mapProps(
     ({jsonData, keyName}) => ({ image: jsonData[keyName] }) 
    ) 
)(ReadyView); 

const ThisPage = <Page request={new Request("//api.github.com/emojis")} keyName="smile" /> 

//That's it! 

ReactDOM.render(ThisPage, document.getElementById("app")); 


/* 
* Imaginary third party HOC 
*/ 

interface FetchJsonProps { 
    request: Request; 
} 
function _FetchJson(WrappedComponent) { 
    return class extends React.Component<FetchJsonProps> { 
     componentDidMount() { 
      fetch(this.props.request) 
       .then(response => response.json()) 
       .then(this.setState.bind(this)); 
     } 

     render() { 
      return <WrappedComponent jsonData={this.state} {...this.props} /> 
     } 
    } 
} 

我怎樣才能改變這種狀況_FetchJson到也在重構內工作?最有用的(不只是我 - 但僅供參考)將兩種解決方案:

  1. 隨着lifecycle()
  2. 隨着mapPropsStream()

注:我沒有做在生命週期的嘗試()方法但沒有工作:

const _FetchJson = compose(
    withStateHandlers(undefined, 
     { 
      onData: state => ({ 
       jsonData: state 
      }) 
     }), 
     lifecycle({ 
      componentDidMount() { 
       fetch(this.props.request) 
       .then(response => response.json()) 
       .then(this.props.onData.bind(this)); 
      } 
     }) 
    ); 

回答

1

你去那裏:

const fetchJson = compose(
    withStateHandlers(null, { 
    onData: state => data => ({ 
     jsonData: data 
    }) 
    }), 
    lifecycle({ 
    componentDidMount() { 
     fetch(this.props.request) 
     .then(response => response.json()) 
     .then(data => this.props.onData(data)); 
    } 
    }) 
); 
+0

謝謝!是的,我錯過了withStateHandlers回調expect(state,props)=> payload => {}而不僅僅是(state,props)=> {};) – davidkomer