与 recompose() 异步的示例?

Example of async with recompose()?

我有以下代码可以完全工作,尽管其中一部分 (_FetchJSON) 是 recompose 之外的自定义 HOC

(现场演示@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()

注意:我确实尝试过 lifecycle() 方法但没有成功:

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));
            }
        })
    );

好了:

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));
    }
  })
);