【问题标题】:Example of async with recompose()?使用 recompose() 进行异步的示例?
【发布时间】:2018-01-24 21:41:44
【问题描述】:

我有以下完全可以工作的代码,尽管其中一部分 (_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 更改为也可以在 recompose 中使用?最有帮助(不仅对我 - 而是供参考)将是两个解决方案:

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

【问题讨论】:

    标签: reactjs recompose


    【解决方案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));
        }
      })
    );
    

    【讨论】:

    • 谢谢!是的,我错过了 withStateHandlers 回调期望 (state,props) => payload => {} 而不仅仅是 (state,props) => {} ;)
    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2021-02-17
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多