gpt4 book ai didi

reactjs - react useEffect : Outer scope values like 'authService._user' aren't valid dependencies because mutating them doesn't re-render the component

转载 作者:行者123 更新时间:2023-12-05 05:08:33 25 4
gpt4 key购买 nike

我想使用 useEffect 检查用户是否在菜单上登录打印用户名。但我收到这个警告:

React Hook useEffect has an unnecessary dependency: 'authService._user'. Either exclude it or remove the dependency array. Outer scope values like 'authService._user' aren't valid dependencies because mutating them doesn't re-render the component react-hooks/exhaustive-deps

这是我在 navbar 中的 useEffect:

    useEffect(() => {
setUsername(authService._user.username);
}, [authService._user])

这是我的授权服务示例:

interface User {
username: string;
password: string;
}
export class AuthorizeService {
_user: User = {
username: '',
password: ''
};
_isAuthenticated = false;

isAuthenticated() {
return this._isAuthenticated;
}

Authenticate(username: string, password: string) {
this._isAuthenticated = true; //I will add fetch latter here
this._user = {
username: username,
password: password
}
}
}

const authService = new AuthorizeService();

export default authService;

顺便说一句,一切正常,但控制台中有警告。

我的问题是:这样做是否正确?以及为什么会有警告。

最佳答案

只有当它来自 props 时才需要填充该数组。

看看https://en.reactjs.org/docs/hooks-effect.html在“提示:通过跳过效果优化性能”部分

但我建议阅读有关 useEffects 的整个文档,那里有一些重要的细节和简短的文档。

关于reactjs - react useEffect : Outer scope values like 'authService._user' aren't valid dependencies because mutating them doesn't re-render the component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209623/

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