我有下面的代码可以完全工作,尽管其中的一部分(_FetchJSON)是一个自定义的自定义外部重组
(实时演示@ 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));
}
})
);发布于 2017-08-20 12:38:28
就这样吧:
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));
}
})
);https://stackoverflow.com/questions/45718764
复制相似问题