TL; DR. , . HoC, .
, -, /, . : " ? , ..". , Relay, . Relay , , , "". .
, componentDidMount , "".
, , :
/services/ServicesContainer/services/10, , .- , , , .
, , , , , . - :
class Services extends React.Component {
componentDidMount() {
if (!this.props.areServicesFetched) {
this.props.fetchServices()
}
}
render() {
return this.props.areServicesFetched ? (
<ul>
{this.props.services.map(service => <Service key={service.id} {...service}/>)}
</ul>
) : <p>{'Loading...'}</p>
}
}
const ServicesContainer = connect(
(state) => ({
areServicesFetched: areServicesFetched(state) // it a selector, not shown in this example
services: getServices(state) // it also a selector returning the services array or an empty array
}),
(dispatch) => ({
fetchServices() {
dispatch(fetchServices()) // let say fetchServices is the async action that fetch services
}
})
)(Services)
const Service = ({ id, name }) => (
<li>{name}</li>
)
. , . , .
- " , ?" . , ? :
, , . , .
, , , ( , , " ?" ..). , :
const Services = ({ services }) => (
<ul>
{services.map(service => <Service key={service.id} {...service}/>)}
</ul>
)
Services.propTypes = {
services: React.PropTypes.arrayOf(React.PropTypes.shape({
id: React.PropTypes.string,
}))
}
const Service = ({ id, name }) => (
<li>{name}</li>
)
Service.propTypes = {
id: React.PropTypes.string,
name: React.PropTypes.string
}
, , , . . " , , - ". HoC.
, HoC , , . HoC - , , .
, , , . recompose - , HoC.
, ensureServices, :
connectservices- ,
services services
:
const ensureServices = (PureComponent, LoadingComponent) => {
const identity = t => t
const spinnerWhileLoading = hasLoaded =>
branch(
hasLoaded,
identity,
renderComponent(LoadingComponent)
)
return connect(
(state) => ({
areAllServicesFetched: areAllServicesFetched(state),
services: getServices(state)
}),
(dispatch) => ({
fetchServices: dispatch(fetchServices())
})
)(compose(
lifecycle({
componentDidMount() {
if (!this.props.areAllServicesFetched) {
this.props.fetchServices()
}
}
}),
spinnerWhileLoading(props => props.areAllServicesFetched),
mapProps(props => ({ services: props.services }))
)(PureComponent))
}
, services , :
const Loading = () => <p>Loading...</p>
const ServicesContainer = ensureServices(Services, Loading)
<Services> , , , <ServicesForm>, services , - :
const ServicesFormContainer = ensureServices(ServicesForm, Loading)
, react-redux-pledge, , , .