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