Пример асинхронности с recompose()?

У меня есть следующий код, который работает полностью, хотя одна его часть (_FetchJSON) является настраиваемым 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));
            }
        })
    );

person davidkomer    schedule 16.08.2017    source источник


Ответы (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));
    }
  })
);
person thedude    schedule 20.08.2017
comment
Благодарность! да, я пропустил, что обратные вызовы withStateHandlers ожидают (state, props) => payload => {}, а не просто (state, props) => {};) - person davidkomer; 20.08.2017