import axios from "axios";
import { useEffect, useState, useCallback } from "react";
export default function App() {
const [user, setUser] = useState([]);
const getUser = useCallback(async () => {
let { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
setUser(data);
}, [user]);
useEffect(() => {
getUser();
}, [getUser]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
(我可以从useEffect依赖项中删除getUser并删除useCallback,这将完美地工作),但我想尝试将getUser放在useEffect依赖项中,同时这样做需要在useCallback中包装getUser。在useCallback依赖,我把setUser它工作得很好,但在把用户作为useCallback依赖m得到无限循环的情况下。
如果getUser
发生变化,效果将运行:
useEffect(() => {
//...
}, [getUser]);
如果user
发生变化,getUser
也会发生变化:
const getUser = useCallback(async () => {
//...
}, [user]);
和getUser
改变user
:
setUser(data);
所以当组件呈现时,效果执行,调用getUser
,更新user
,改变getUser
,触发效果,调用getUser
,等等
getUser
的useCallback
不依赖于user
,只依赖于setUser
。更改它的依赖数组以反映:
const getUser = useCallback(async () => {
//...
}, [setUser]);
setUser
不会改变,所以getUser
不会改变,所以效果不会被重新调用。