gpt4 book ai didi

reactjs - React with TypeScript - React 检测到 ComponentName 调用的 Hooks 的顺序发生了变化

转载 作者:行者123 更新时间:2023-12-02 01:37:17 26 4
gpt4 key购买 nike

我正在与用户一起处理一个项目。现在我正在使用 UserProfile

这是我收到的错误。

React has detected a change in the order of Hooks called by UserProfile

Previous render Next render
------------------------------------------------------
1. useState useState
2. useContext useContext
3. useEffect useEffect
4. undefined useContext

让我展示一些 UserProfile 组件的代码。

export const UserProfile = () => {
document.title = `${title} - My Profile`;
const [profile, setProfile] = useState<UserDetails>();

const {claims} = useContext(AuthContext);

const getUserEmail = (): string => {
return claims.filter(x => x.name === "email")[0]?.value.toString();
}

useEffect(() => {
axios.get(`${urlAuth}?userName=${getUserEmail()}`)
.then((response: AxiosResponse<UserDetails>) => {
setProfile(response.data);
})
}, [getUserEmail]);

return (
profile ?
<article>
<h1>This profile belongs to {UserName()}</h1>
<h2>{profile.name}</h2>
</article>
: <div>Loading...</div>
)
}

我在 getUserEmail 函数中收到警告,

它说

    The 'getUserEmail' function makes the dependencies of useEffect Hook (at line 26) change on every render. 
Move it inside the useEffect callback.
Alternatively, wrap the definition of 'getUserEmail' in its own useCallback() Hook.

我不确定应该如何完成。关于我可以做什么的任何想法?

谢谢

最佳答案

将 getUserEmail 的值包装在 useCallback 中。在每次渲染时,getUserEmail 基本上变成了一个"new"函数。

当 useEffect 或其他类似钩子(Hook)的 deps 数组中有函数时,React 通过引用检查它。由于每个组件函数执行/重新渲染都会导致创建一个新函数,因此您的 useEffect Hook 实际上每次都会运行,将您送入重新渲染循环(因为它将运行 useEffect,使用 setProfile 更新状态,这反过来将触发另一次执行,其中 getUserEmail 再次不同,导致 useEffect 再次运行,依此类推。

const getUserEmail = useCallback((): string => {
return claims.filter(x => x.name === "email")[0]?.value.toString();
}, [claims]);

这应该会给你一个内存回调,只有在声明发生变化时才会重新创建。由于声明来自您的上下文,因此作为依赖项应该是安全的。

关于reactjs - React with TypeScript - React 检测到 ComponentName 调用的 Hooks 的顺序发生了变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72153721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com