为两个redux动作提供可重用的功能

问题描述 投票:0回答:1

我正在尝试使代码块不太可重复且更可重用,但是我无法确定。我有这么大的代码块,显然可以完成相同的操作,只是调度了我导入的另一个redux动作:

  const handleSend = async (values) => {
    if (props.onSubmit) {
      props.onSubmit(values);
    }

    if (source === 'First Source') {
      const { error } = await props.dispatch(
        shareFirstSource(payload, values.email, values.message, values.encrypt, values.phone)
      );

      if (error) {
        Alert.alert('Email did not send.', 'Sorry for the inconvenience.', [
          { text: 'Try Again?', onPress: () => handleSend(values) },
          { text: 'Cancel' }
        ]);
      } else {
        Alert.alert('Email Sent', 'Your email was successfully sent.', [
          { text: 'OK', onPress: () => props.navigation.dismiss() }
        ]);
      }
    }

    if (source === 'Second Source') {
      const { error } = await props.dispatch(
        shareSecondSource(payload, values.email, values.message, values.encrypt, values.phone)
      );

      if (error) {
        Alert.alert('Email did not send.', 'Sorry for the inconvenience.', [
          { text: 'Try Again?', onPress: () => handleSend(values) },
          { text: 'Cancel' }
        ]);
      } else {
        Alert.alert('Email Sent', 'Your email was successfully sent.', [
          { text: 'OK', onPress: () => props.navigation.dismiss() }
        ]);
      }
    }
  };

我设法将其分解为这段代码,但是我一直遇到问题。我正在遇到的当前问题是,sendAction回来是不确定的。

  const transmitActions = {
    FirsSource: shareFirstSource,
    SecondSource: shareSecondSource,
  };

  const handleSend = async (values) => {
    if (props.onSubmit) {
      props.onSubmit(values);
    }

    const transmitAction = transmitActions[source];

    console.log('TRANSMIT_ACTION>>>', transmitAction);

    if (!transmitAction) {
      return;
    }

    const { error } = await props.dispatch(transmitAction(payload, values.email, values.message, values.encrypt, values.phone));

    if (error) {
      Alert.alert('Email did not send.', 'Sorry for the inconvenience.', [
        { text: 'Try Again?', onPress: () => handleSend(values) },
        { text: 'Cancel' }
      ]);
    } else {
      Alert.alert('Email Sent', 'Your email was successfully sent.', [
        { text: 'OK', onPress: () => props.navigation.dismiss() }
      ]);
    }
  }

我认为部分原因是我对TypseScript不熟悉,因为我以前遇到过TS问题,但我能够解决。第二组眼睛将不胜感激。

javascript typescript function react-native dry
1个回答
0
投票

也许我缺少一些上下文,但是我不太理解代码背后的想法。您能否分享一个最小的无效示例?

根据我在第二段代码中看到的,'source'变量看起来没有定义。也许这就是为什么'transmissionAction'未定义的原因。

© www.soinside.com 2019 - 2024. All rights reserved.