Created
December 19, 2016 15:44
-
-
Save suhaotian/5ba34a78aecbc71db4e6413dd70a858e to your computer and use it in GitHub Desktop.
React Fetch Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component, PropTypes } from 'react' | |
| //import styles from './style.css' | |
| class ComponentName extends Component { | |
| // static defaultProps = {} | |
| static propTypes = { | |
| promises: PropTypes.array.isRequired, | |
| children: PropTypes.func.isRequired, | |
| } | |
| state = { | |
| error: null, | |
| fetching: true, | |
| data: null, | |
| } | |
| // shouldComponentUpdate(nextProps, nextState) {} | |
| componentDidMount() { | |
| const { promises } = this.props | |
| Promise.all(promises) | |
| .then(result => { | |
| if (this.willUnmout) return | |
| this.setState({ | |
| fetching: false, | |
| data: result, | |
| }) | |
| }) | |
| .catch(e => { | |
| if (this.willUnmout) return | |
| this.setState({fetching: false, error: e}) | |
| }) | |
| } | |
| componentWillUnmount() { | |
| this.willUnmount = true | |
| } | |
| render() { | |
| const {error, fetching, data,} = this.state | |
| if (fetching) return <div>loading</div> | |
| else if (data) return this.props.children(data) | |
| else return <div>{error.toString()}</div> | |
| } | |
| } | |
| export default ComponentName |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment