injectReducer.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import React from 'react'
  2. import hoistNonReactStatics from 'hoist-non-react-statics'
  3. import { ReactReduxContext } from 'react-redux'
  4. import getInjectors from './reducerInjectors'
  5. /**
  6. * Dynamically injects a reducer
  7. *
  8. * @param {string} key A key of the reducer
  9. * @param {function} reducer A reducer that will be injected
  10. *
  11. */
  12. export default ({ key, reducer }) => (WrappedComponent) => {
  13. class ReducerInjector extends React.Component {
  14. public static WrappedComponent = WrappedComponent
  15. public static contextType = ReactReduxContext
  16. public static displayName = `withReducer(${WrappedComponent.displayName ||
  17. WrappedComponent.name ||
  18. 'Component'})`
  19. constructor (props, context) {
  20. super(props, context)
  21. getInjectors(context.store).injectReducer(key, reducer)
  22. }
  23. public render () {
  24. return <WrappedComponent {...this.props} />
  25. }
  26. }
  27. return hoistNonReactStatics(ReducerInjector, WrappedComponent)
  28. }
  29. const useInjectReducer = ({ key, reducer }) => {
  30. const context = React.useContext(ReactReduxContext)
  31. React.useEffect(() => {
  32. getInjectors(context.store).injectReducer(key, reducer)
  33. }, [])
  34. }
  35. export { useInjectReducer }