1

我正在尝试访问 HOC 之外的道具。我正在尝试以暗方式设置启动,并且我需要 clientSideID 基于设置是动态的。我似乎无法弄清楚我做错了什么。withLDProvider 是一个需要包装整个应用程序的函数。有人可以帮我吗?太感谢了!

import React from 'react';
import PropTypes from 'prop-types';
import { withLDProvider } from 'launchdarkly-react-client-sdk';
import { get } from 'lodash';
import { getEnv } from '../helpers/env';
import { LAUNCH_DARKLY } from '../constants/launchdarkly';

const LaunchDarklyProvider = ({ clientSideID }) => {
  console.log('clientSideID provider', clientSideID);
  const LDComponent = withLDProvider({
    clientSideID,
  });

  return <LDComponent />;
};

LaunchDarklyProvider.propTypes = {
  clientSideID: PropTypes.string,
};

const LDProvider = WrappedComponent => {
  const environment = getEnv();
  const { LOCAL, TEST } = LAUNCH_DARKLY;

  const LDProviderHOC = props => {
    const { local } = props;
    const { settings } = local;
    let clientId;

    switch (environment) {
      case 'test':
        clientId = TEST;
        break;
      case 'local':
        clientId = LOCAL;
        break;
      case 'production':
        clientId = get(settings, 'launchDarkly.clientSideId', '');
        break;
      default:
        break;
    }

    return <WrappedComponent {...props} clientSideID={clientId} />;
  };

  LDProviderHOC.propTypes = {
    local: PropTypes.object,
  };

  return LDProviderHOC;
};

export const ToggleProvider = () => LDProvider(LaunchDarklyProvider);
4

1 回答 1

2

首先,为什么不将您的 clientSideId 配置为 env var 并让您的构建(即 webpack 等)将其注入而不是使用 switch 语句?

如果您一定要像上面那样阅读配置,为什么不使用基本实现:

import { withLDProvider } from 'launchdarkly-react-client-sdk';
import { get } from 'lodash';
import { getEnv } from '../helpers/env';
import { LAUNCH_DARKLY } from '../constants/launchdarkly';

const environment = getEnv();
const { LOCAL, TEST } = LAUNCH_DARKLY;
let clientId;
switch (environment) {
  case 'test':
    clientId = TEST;
    break;
  case 'local':
    clientId = LOCAL;
    break;
  case 'production':
    clientId = get(settings, 'launchDarkly.clientSideId', '');
    break;
  default:
    break;
}

export default withLDProvider({ 
  clientSideID: clientId,
  user: {
    "key": "aa0ceb",
    "name": "Grace Hopper",
    "email": "gracehopper@example.com"
  },
  options: { /* ... */ }
})(YourApp);
于 2020-03-23T17:03:52.653 回答