Created
November 21, 2018 13:24
-
-
Save cheton/c872b5b8c8109dbe663f9ccf54b0d480 to your computer and use it in GitHub Desktop.
Carousel
This file contains 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 PropTypes from 'prop-types'; | |
import React from 'react'; | |
class Carousel extends React.Component { | |
static propTypes = { | |
limit: PropTypes.number, | |
total: PropTypes.number, | |
data: PropTypes.oneOfType([ | |
PropTypes.object, | |
PropTypes.array | |
]) | |
}; | |
_mounted = false; | |
static getDerivedStateFromProps(props, state) { | |
let nextState = null; | |
if ((props.limit !== state.next.limit) || | |
(props.total !== state.next.total) || | |
(props.data !== state.next.data)) { | |
const { | |
limit = state.next.limit, | |
total = state.next.total, | |
data = state.next.data, | |
} = props; | |
nextState = { | |
next: { | |
limit, | |
total, | |
data | |
} | |
}; | |
} | |
return nextState; | |
} | |
constructor(props) { | |
super(props); | |
const limit = Number(this.props.limit) || 0; | |
const total = Number(this.props.total) || 0; | |
this.state = { | |
current: { | |
offset: 0, | |
limit: limit, | |
total: total, | |
data: this.props.data, | |
}, | |
next: { | |
limit: limit, | |
total: total, | |
data: this.props.data, | |
} | |
}; | |
} | |
next = () => { | |
if (!this._mounted) { | |
return; | |
} | |
this.setState(state => { | |
const { current, next } = state; | |
const { offset, limit, total, data } = current; | |
if (offset + limit >= total) { | |
const { | |
limit: nextLimit = limit, | |
total: nextTotal = total, | |
data: nextData = data | |
} = next; | |
return { | |
current: { | |
offset: 0, | |
limit: nextLimit, | |
total: nextTotal, | |
data: nextData | |
} | |
}; | |
} | |
return { | |
current: { | |
offset: offset + limit, | |
limit, | |
total, | |
data | |
} | |
}; | |
}); | |
}; | |
componentDidMount() { | |
this._mounted = true; | |
} | |
componentWillUnmount() { | |
this._mounted = false; | |
} | |
render() { | |
const { | |
current: { offset, limit, total, data } | |
} = this.state; | |
const next = this.next; | |
return this.props.children({ | |
offset, | |
limit, | |
total, | |
data, | |
next, | |
}); | |
} | |
} | |
export default Carousel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment