如何在另一个自定义钩子中使用返回值的自定义钩子? [英] How to use a custom-hook that returns a value, inside another custom Hook?

查看:34
本文介绍了如何在另一个自定义钩子中使用返回值的自定义钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是REACTIVE-Native,在其中,我有一个名为useUser的自定义Hook,它使用Auth.getUserInfro方法从AWS Amplify获取用户信息,然后获取返回对象的一部分并使用它设置状态变量。我还有另一个名为useData的钩子,它根据用户ID获取一些数据并将其设置为状态变量。

使用用户自定义挂钩:

import React, { useState, useEffect } from "react";
import { Auth } from "aws-amplify";

const getUserInfo = async () => {
  try {
    const userInfo = await Auth.currentUserInfo();
    const userId = userInfo?.attributes?.sub;
    return userId;
  } catch (e) {
    console.log("Failed to get the  AuthUserId", e);
  }
};

const useUserId = () => {
  const [id, setId] = useState("");

  useEffect(() => {
    getUserInfo().then((userId) => {
      setId(userId);
    });
  }, []);

  return id;
};

export default useUserId;
import useUserId from "./UseUserId";
// ...rest of the necessary imports

const fetchData = async (userId) = > { // code to fetch data from GraphQl}

const useData = () => {
    const [data, setData] = useState();
    
    useEffect(() => { 
        const userId = useUser();
        fetchData(userId).then( // the rest of the code to set the state variable data.)
    },[])

    return data
   }

当我尝试执行此操作时,收到错误提示

*错误:挂钩调用无效。只能在函数组件的主体内部调用挂钩。这可能是由于以下原因之一:

  1. 您的Reaction和呈现器的版本可能不匹配(如Reaction DOM)
  2. 您可能违反了钩子规则
  3. 您可能在同一应用程序中有多个Reaction副本 有关如何调试和修复此问题的提示,请参阅https://reactjs.org/link/invalid-hook-call。*

我认为问题在于我在Use效果内部调用了Hook useUser,但在函数内部使用它会导致here描述的问题,我不能在fetchData的主体之外使用它,因为useData本身是一个钩子,它只能在函数组件的主体或Hook的主体内使用。所以我不知道如何找到解决这个问题的方法。

推荐答案

正确,Reaction挂钩只能从Reaction函数组件和其他Reaction挂钩调用。useEffect钩子的回调不是反应钩子,而是回调。根据Rules of Hooks,不要在循环、条件或嵌套函数内调用挂钩。

我建议重构useData挂钩以将userId作为参数使用,以在useEffect的依赖项数组中使用。

const fetchData = async (userId) => {
  // code to fetch data from GraphQl
};

const useData = (userId) => {
  const [data, setData] = useState();
    
  useEffect(() => { 
    fetchData(userId)
      .then((....) => {
        // the rest of the code to set the state variable data.
      });
  }, [userId]);

  return data;
};

功能组件中的用法:

const userId = useUser();
const data = useData(userId);

如果这是通常配对的东西,则将其抽象为单个挂钩:

const useGetUserData = () => {
  const userId = useUser();
  const data = useData(userId);
  return data;
};

...

const data = useGetUserData();

不过,您可能应该只将其实现为单个钩子,如下所示:

const useGetUserData = () => {
  const [data, setData] = useState();

  useEffect(() => {
    getUserInfo()
      .then(fetchData) // shortened (userId) => fetchData(userId)
      .then((....) => {
        // the rest of the code to set the state variable data.
        setData(....);
      });
  }, []);

  return data;
};

这篇关于如何在另一个自定义钩子中使用返回值的自定义钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆