【问题标题】:Invalid use of Hooks when using onPress to call a function使用 onPress 调用函数时使用 Hooks 无效
【发布时间】:2021-06-28 17:02:09
【问题描述】:

我遇到了这个 Invalid hook call 的问题。 AltIconButton 是一个组件,我使用 redirect={GoogleLogin} 放置在导出默认函数中 这是我的 login.js sn-p:

const AltIconButton = (props) => {
  console.log(props.name);
  return (
    <TouchableOpacity activeOpacity={0.5} onPress={props.redirect}>
      <MaterialCommunityIcons
        style={{
          marginHorizontal: 15,
        }}
        name={props.name}
        size={48}
        color="white"
      />
    </TouchableOpacity>
  );
};

那么这是我的 google_login:

function GoogleLogin() {
  const navigation = useNavigation();
  const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
    expoClientId: Constants.manifest.extra.google.WEB_CLIENT_ID,
  });

  useEffect(() => {
    if (response?.type === "success") {
      const { id_token } = response.params;
      const credential = Firebase.auth.GoogleAuthProvider.credential(id_token);
      Firebase.auth()
        .signInWithCredential(credential)
        .then(() => {
          navigation.replace("Home");
        });
    }
  }, [response]);

  return;
}

编辑: 这是我实现 AltIconButton 组件的另一个 sn-p

  <View style={styles.bottomBody}>
    <AltIconButton name="facebook" redirect={FBLogin}></AltIconButton>
    <AltIconButton name="google"redirect={GoogleLogin}></AltIconButton>
  </View>

【问题讨论】:

  • 您是如何使用 AltIconButton 组件的?例如。分享您放置 的代码
  • 编辑了帖子,添加了 AltIconButton 的 sn-p。
  • 好的,你的 GoogleLogin 函数是一个简单的 JS 函数(不是 React 组件)。你不能为 ex 使用钩子。 useNavigationuseEffect 在 JavaScript 函数中。reactjs.org/docs/…
  • 所以我假设我应该将 GoogleLogin 更改为包含我想要的东西的组件?
  • 是的,但我不确定您想要实现什么以及您的身份验证流程是什么。

标签: reactjs react-native expo


【解决方案1】:

通过将JS函数改成自己的组件来解决问题。

例如:

function GoogleLogin() {
  const navigation = useNavigation();
  const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
    expoClientId: Constants.manifest.extra.google.WEB_CLIENT_ID,
  });

  useEffect(() => {
    if (response?.type === "success") {
      const { id_token } = response.params;
      const credential = Firebase.auth.GoogleAuthProvider.credential(id_token);
      Firebase.auth()
        .signInWithCredential(credential)
        .then(() => {
          navigation.replace("Home");
        });
    }
  }, [response]);

  return (
    <TouchableOpacity
      disabled={!request}
      activeOpacity={0.5}
      onPress={() => promptAsync()}
    />
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2021-12-26
    • 2018-10-28
    • 2021-03-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多