2017-08-16 38 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