你好,我在使用 React 的 useEffect
钩子时遇到了问题。下面的代码可以正常工作,但是 es-lint 建议我在依赖数组中从 useEffect
提供依赖项。
带有// eslint-disable-next-line react-hooks/exhaustive-deps
的工作代码
export default function UsersList() {
const [users, setUsers] = useState<User[]>([]);
const { setError } = useContext(errorContext);
const { isLoading, setIsLoading } = useContext(globalContext);
useEffect(() => {
if (users.length < 1) {
fetchUsers();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function fetchUsers () {
try {
setIsLoading(true);
const fetchedUsers = await api.getUsers();
setUsers(fetchedUsers);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}
}
无限循环代码
我试图写出这样的代码,但它会触发一个无限循环...(因为函数内部不断地修改状态并因为声明的依赖项而引发 useEffect
)
useEffect(() => {
async function fetchUsers () {
try {
setIsLoading(true);
const fetchedUsers = await api.getUsers();
setUsers(fetchedUsers);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}
if (users.length < 1) {
fetchUsers();
}
}, [setIsLoading, setError, users]);
我还尝试将fetchUsers()
放入依赖项数组中,但这没有任何效果。
如何正确设置异步调用以在组件挂载时进行,而无需使用// eslint-disable-next-line react-hooks/exhaustive-deps
?