【发布时间】:2020-10-10 15:19:11
【问题描述】:
您好,我在 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?
【问题讨论】:
标签: javascript reactjs typescript react-hooks use-effect