У меня есть следующий код, который работает полностью, хотя одна его часть (_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} />
}
}
}
Как я могу изменить этот _FetchJson
, чтобы он также работал при перекомпоновке? Наиболее полезными (не только для меня, но и для справки) будут два решения:
- С
lifecycle()
- С
mapPropsStream()
примечание: я пытался применить метод lifecycle(), но он не сработал:
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));
}
})
);