react.js.flow 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // @flow
  2. import React, { PureComponent } from 'react' // eslint-disable-line import/no-unresolved
  3. import type { Node } from 'react' // eslint-disable-line import/no-unresolved
  4. import type { Persistor } from '../types'
  5. type Props = {
  6. onBeforeLift?: Function,
  7. children: Node | Function,
  8. loading: Node,
  9. persistor: Persistor,
  10. }
  11. type State = {
  12. bootstrapped: boolean,
  13. }
  14. export class PersistGate extends PureComponent<Props, State> {
  15. static defaultProps = {
  16. children: null,
  17. loading: null,
  18. }
  19. state = {
  20. bootstrapped: false,
  21. }
  22. _unsubscribe: ?Function
  23. componentDidMount() {
  24. this._unsubscribe = this.props.persistor.subscribe(
  25. this.handlePersistorState
  26. )
  27. this.handlePersistorState()
  28. }
  29. handlePersistorState = () => {
  30. const { persistor } = this.props
  31. let { bootstrapped } = persistor.getState()
  32. if (bootstrapped) {
  33. if (this.props.onBeforeLift) {
  34. Promise.resolve(this.props.onBeforeLift())
  35. .finally(() => this.setState({ bootstrapped: true }))
  36. } else {
  37. this.setState({ bootstrapped: true })
  38. }
  39. this._unsubscribe && this._unsubscribe()
  40. }
  41. }
  42. componentWillUnmount() {
  43. this._unsubscribe && this._unsubscribe()
  44. }
  45. render() {
  46. if (process.env.NODE_ENV !== 'production') {
  47. if (typeof this.props.children === 'function' && this.props.loading)
  48. console.error(
  49. 'redux-persist: PersistGate expects either a function child or loading prop, but not both. The loading prop will be ignored.'
  50. )
  51. }
  52. if (typeof this.props.children === 'function') {
  53. return this.props.children(this.state.bootstrapped)
  54. }
  55. return this.state.bootstrapped ? this.props.children : this.props.loading
  56. }
  57. }