我有以下代码完全可以工作,虽然它的一部分(_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} />
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何更改它_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));
}
})
);
Run Code Online (Sandbox Code Playgroud)
你去:
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));
}
})
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2551 次 |
| 最近记录: |