[英][Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component
Hello I am making a react native app.你好我正在制作一个反应原生应用程序。 This is my first react-native project and second project using react.这是我的第一个 react-native 项目和第二个使用 react 的项目。 Anyway I am getting this error in my react native project.无论如何,我在我的 react native 项目中遇到了这个错误。 I am posting my modules please help me.我正在发布我的模块,请帮助我。
So this is my module which uploads the profile picture to my express server.所以这是我的模块,它将个人资料图片上传到我的快递服务器。
const updateProfilePicture = image => {
try {
console.log("Update profile picture hit");
const { user: token } = useAuth();
console.log(`Token received: ${token}`);
const data = new FormData();
console.log(image);
let fileName = image.split("/");
fileName = fileName[fileName.length-1]
console.log(`File name: ${fileName}`)
let extensionName = fileName.split(".");
extensionName = extensionName[extensionName.length-1];
console.log(`Extension name: ${extensionName}`)
data.append('token', token);
data.append('pimage', {
name: Random.getRandomBytes(8).toString('hex')+"."+extensionName,
type: 'image/'+extensionName,
uri: image
});
console.log(`This is the data\n`+data);
return authClient.post(endpointUpdatePicture, data);
} catch(error) {
console.log("Error in update profile picture", error);
}
};
From hit and try I found that the line const { user: token } = useAuth();
从 hit and try 我发现行const { user: token } = useAuth();
is making it wrong.弄错了。
Before going forward, useAuth() is my custom hook for tracking down user.在继续之前,useAuth() 是我用于跟踪用户的自定义钩子。 user is actually a jwt token. user 实际上是一个 jwt 令牌。
Here is my useAuth()这是我的 useAuth()
import { useContext } from 'react';
import authStorage from './storage';
import AuthContext from './context';
import jwt from 'jwt-decode';
export default useAuth = () => {
const {user, setUser} = useContext(AuthContext);
const { name, rating, number, uri } = jwt(user);
const logout = () => {
setUser(null);
authStorage.removeToken();
}
console.log(`Uri: ${uri}`);
return { user, setUser, logout, name, rating, number, uri };
}
Now I have created a context in my App.js from where I get this user and setUser basically the token.现在我在我的 App.js 中创建了一个上下文,从中我得到了这个用户和 setUser 基本上是令牌。 Writing this line is throwing me the hook error.写这行代码给我带来了钩子错误。
Please help me in 2 ways:请通过两种方式帮助我:
since your updateProfilePicture
is not called at your component body, you should change it to receive as param your token.由于您的组件主体未调用您的updateProfilePicture
,因此您应该将其更改为作为参数接收您的令牌。
Then at your Component
you can call your hook useAuth
at component body, extracting the desired token.然后在您的Component
中,您可以在组件主体处调用您的钩子useAuth
,提取所需的令牌。 This way you can pass it as variable to updateProfilePicture
without facing any error, since useAuth
will be called correctly at your function body.这样,您可以将其作为变量传递给updateProfilePicture
而不会遇到任何错误,因为useAuth
将在您的 function 主体上正确调用。
your code would look something like:你的代码看起来像:
const updateProfilePicture = (image, token) => {
// ... same code here without 'useAuth'
}
const Component = ({ image }) => {
const { user: token } = useAuth();
const onsubmit = () => updateProfilePicture(img, token)
return (
<>
<div>upload here image</div>
<button onClick={() => onsubmit(image, token)}>upload</button>
</>
)
}
Hooks in react functional components have to be used in the main component function or as a part of custom hooks, without conditions, loops, or callbacks. react 功能组件中的钩子必须在主组件 function 中使用,或者作为自定义钩子的一部分,没有条件、循环或回调。 You have to move useAuth hook to the main component function, outside try-catch block, and outside updateProfilePicture function .您必须将 useAuth 挂钩移动到主要组件 function、try-catch 块之外和 updateProfilePicture function 之外。
According to React Documentation根据反应文档
Don't call Hooks inside loops, conditions, or nested functions.不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function, before any early returns.相反,在任何提前返回之前,始终在 React function 的顶层使用 Hooks。 By following this rule, you ensure that Hooks are called in the same order each time a component renders.通过遵循此规则,您可以确保每次渲染组件时都以相同的顺序调用 Hook。 That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.这就是允许 React 在多个 useState 和 useEffect 调用之间正确保留 Hooks 的 state 的原因。
✅ Call Hooks from React function components. ✅ 从 React function 组件调用 Hooks。
✅ Call Hooks from custom Hooks (we'll learn about them on the next page). ✅ 从自定义 Hooks 调用 Hooks(我们将在下一页了解它们)。
Your useAuth
hook is called inside try-catch
block.您的useAuth
钩子在try-catch
块内被调用。 Instead, call it at top-level of the functional component相反,在功能组件的顶层调用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.