Provider.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import React, { useMemo, useEffect } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { ReactReduxContext } from './Context';
  4. import Subscription from '../utils/Subscription';
  5. function Provider(_ref) {
  6. var store = _ref.store,
  7. context = _ref.context,
  8. children = _ref.children;
  9. var contextValue = useMemo(function () {
  10. var subscription = new Subscription(store);
  11. subscription.onStateChange = subscription.notifyNestedSubs;
  12. return {
  13. store: store,
  14. subscription: subscription
  15. };
  16. }, [store]);
  17. var previousState = useMemo(function () {
  18. return store.getState();
  19. }, [store]);
  20. useEffect(function () {
  21. var subscription = contextValue.subscription;
  22. subscription.trySubscribe();
  23. if (previousState !== store.getState()) {
  24. subscription.notifyNestedSubs();
  25. }
  26. return function () {
  27. subscription.tryUnsubscribe();
  28. subscription.onStateChange = null;
  29. };
  30. }, [contextValue, previousState]);
  31. var Context = context || ReactReduxContext;
  32. return React.createElement(Context.Provider, {
  33. value: contextValue
  34. }, children);
  35. }
  36. if (process.env.NODE_ENV !== 'production') {
  37. Provider.propTypes = {
  38. store: PropTypes.shape({
  39. subscribe: PropTypes.func.isRequired,
  40. dispatch: PropTypes.func.isRequired,
  41. getState: PropTypes.func.isRequired
  42. }),
  43. context: PropTypes.object,
  44. children: PropTypes.any
  45. };
  46. }
  47. export default Provider;