How to use a custom-hook that returns a value, inside another custom Hook?(如何在另一个自定义钩子中使用返回值的自定义钩子?)
问题描述
我使用的是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
}
当我尝试执行此操作时,收到错误提示
*错误:挂钩调用无效。只能在函数组件的主体内部调用挂钩。这可能是由于以下原因之一:- 您的Reaction和呈现器的版本可能不匹配(如Reaction DOM)
- 您可能违反了钩子规则
- 您可能在同一应用程序中有多个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;
};
这篇关于如何在另一个自定义钩子中使用返回值的自定义钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在另一个自定义钩子中使用返回值的自定义钩子?
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
