我面临获取数据的问题(React、useEffect)
I am facing a problem of fetching data (React, useEffect)
我正在尝试从下面给出的 URL 中获取数据,有时我会获取,但大多数时候不在控制台中。我不知道我用 async-await 尝试过的问题,但结果是一样的。
https://quiet-forest-82433.herokuapp.com/myorders/?email=liza@liza.com
我的代码是:
const {user} = useAuth();
const [totalCart, setTotalCart] = useState({})
useEffect(() => {
const url = `https://quiet-forest-82433.herokuapp.com/myorders/?email=${user?.email}`
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
}, []);
useEffect 应该依赖于 user
。
在您拥有有效的用户电子邮件之前不要调用 fetch。目前,您的代码将要求 email=undefined 直到用户填充,但 useEffect() 不会再次触发,因为不依赖于用户。
useEffect(() => {
if (!user || !user.email) return
const url = `https://quiet-forest-82433.herokuapp.com/myorders/?email=${user?.email}`
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
}, [user]);
我正在尝试从下面给出的 URL 中获取数据,有时我会获取,但大多数时候不在控制台中。我不知道我用 async-await 尝试过的问题,但结果是一样的。
https://quiet-forest-82433.herokuapp.com/myorders/?email=liza@liza.com
我的代码是:
const {user} = useAuth();
const [totalCart, setTotalCart] = useState({})
useEffect(() => {
const url = `https://quiet-forest-82433.herokuapp.com/myorders/?email=${user?.email}`
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
}, []);
useEffect 应该依赖于 user
。
在您拥有有效的用户电子邮件之前不要调用 fetch。目前,您的代码将要求 email=undefined 直到用户填充,但 useEffect() 不会再次触发,因为不依赖于用户。
useEffect(() => {
if (!user || !user.email) return
const url = `https://quiet-forest-82433.herokuapp.com/myorders/?email=${user?.email}`
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
}, [user]);