首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用recompose()的异步示例?

使用recompose()的异步示例?
EN

Stack Overflow用户
提问于 2017-08-16 16:31:15
回答 1查看 3.1K关注 0票数 4

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

(实时演示@ https://codepen.io/dakom/pen/zdpPWV?editors=0010)

代码语言:javascript
复制
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()

注意:我确实尝试过生命周期()方法,但没有成功:

代码语言:javascript
复制
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));
            }
        })
    );
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-20 12:38:28

就这样吧:

代码语言:javascript
复制
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));
    }
  })
);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45718764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档