我是个新手,正在学习如何使用useEffect。我在我的react应用中遇到了这个警告。我在SO上尝试了一些解决方案,但警告仍然存在。fetchUser和fetchPosts都会触发此警告。谁能告诉我问题是什么,警告是什么意思?
App.js
useEffect(() => {
setLoading(true)
const getUser = async () => {
const userFromServer = await fetchUser()
if (userFromServer) {
setUser(userFromServer)
setLoading(false)
} else {
console.log("error")
}
}
getUser()
}, [userId])
useEffect(() => {
const getPosts = async () => {
const postsFromServer = await fetchPosts()
setPosts(postsFromServer)
}
getPosts()
}, [userId])
useEffect(() => {
const getUserList = async () => {
const userListFromServer = await fetchUserList()
setUserList(userListFromServer)
}
getUserList()
}, [])
// Fetch user
const fetchUser = async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
const data = await res.json()
return data
}
// Fetch posts
const fetchPosts = async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
const data = await res.json()
return data
}
// Fetch list of users
const fetchUserList = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users/')
const data = await res.json()
return data
}发布于 2021-02-08 14:56:54
如果您使用的是在useEffect外部声明的任何函数或状态,则需要将其传递到依赖项数组中,如下所示:
const someFunctionA = () => {
....
}
const someFunctionB = () => {
....
}
useEffect(() => {
....
}, [someFunctionA, someFunctionB])你可以在这里阅读更多关于它的信息,如果你想知道它将如何呈现:React useEffect - passing a function in the dependency array
https://stackoverflow.com/questions/66096882
复制相似问题