Redux-persist: Dynamic injection reducer, which cannot be implemented in production environment

Created on 4 Dec 2018  路  2Comments  路  Source: rt2zz/redux-persist

enthusiasm.tsx

const mapStateToProps = (state: IReducers) => ({ enthusiasm: state.enthusiasm });

const withConnect = connect(
  mapStateToProps
);

const persistEnthusiasmConfig = {
  key: 'enthusiasm',
  storage,
  version: 10
};

const reducer = {
  enthusiasm: persistReducer(persistEnthusiasmConfig, enthusiasm)
};

const withReducer = injectReducer<IReducers>(reducer);

export default compose(
  withReducer,
  withConnect
)(Enthusiasm);

injectReducer.ts

import React, { Component } from 'react';
import { ReducersMapObject } from 'redux';
import hoistNonReactStatics from 'hoist-non-react-statics';

import { injectReducer } from '@store';

/**
 * Dynamically injects a reducer
 *
 * @param {function} reducer A reducer that will be injected
 *
 */
export default function <S>(reducer: Partial<ReducersMapObject<S>>) {
  return (WrappedComponent: any) => {

    class ReducerInjector extends Component {
      static WrappedComponent = WrappedComponent;

      constructor(props: object) {
        super(props);
        injectReducer(reducer);
      }

      render() {
        return <WrappedComponent {...this.props}/>;
      }
    }

    return hoistNonReactStatics(ReducerInjector, WrappedComponent);
  };
}

store.ts

export function injectReducer(reducer: Partial<ReducersMapObject<IReducers>>) {
  if (store.injectedReducers) {
    if (Reflect.has(store.injectedReducers, Object.keys(reducer)[0])) {
      return;
    }
    Object.assign(store.injectedReducers, reducer);
    store.replaceReducer(createReducer(store.injectedReducers));
  }
}

This code executes normally in the development environment, but redux-persist does not execute properly after the build

Most helpful comment

@a1992012015 how did you solve this?

All 2 comments

@a1992012015 how did you solve this?

thumb downed the issue for closing it without sharing a solution

Was this page helpful?
0 / 5 - 0 ratings