Reactjs useEffect无限循环网络请求

Reactjs useEffect无限循环网络请求,reactjs,infinite-loop,use-effect,use-state,use-context,Reactjs,Infinite Loop,Use Effect,Use State,Use Context,我在我的网络上收到无限的请求,这是由于我的useEffect。我知道问题是因为我将useffect函数中的'posts'和'setPost'放在括号中作为第二个参数,但是每当我添加新的post时,我都需要呈现页面,因此'posts'必须放在括号中 function Home() { const {userData, setUserData} = useContext(userContext) const [posts, setPost] = useState([]) const [cre

我在我的网络上收到无限的请求,这是由于我的useEffect。我知道问题是因为我将useffect函数中的'posts'和'setPost'放在括号中作为第二个参数,但是每当我添加新的post时,我都需要呈现页面,因此'posts'必须放在括号中

    function Home() {
const {userData, setUserData} = useContext(userContext)
const [posts, setPost] = useState([])
const [createPost, setCreatePost] = useState('')
const handleToken = () => {
    localStorage.removeItem('auth-token')
}

const token = localStorage.getItem("auth-token");

const handleOnSubmit = (e) => {
    e.preventDefault()
    axios.post('http://localhost:5000/posts', {textOfThePost: createPost}, {
        headers: { 'auth-token': token },
    })
    .then((res) => {setCreatePost("")})
    axios.get('http://localhost:5000/posts')
    .then(res => {
        setPost(res.data)
    })
}

useEffect(() => {
}, [posts])

如果您在useEffect内部执行
setPost
,我假设
posts
被更改,并且您在
useEffect
中添加了
posts
作为依赖项,当然它将重新调用,并进入无限循环。确保何时调用
posts
API

const [posts, setPost] = useState([])

useEffect(() => {
   axios.get('http://localhost:5000/posts')
   .then(res => {
     setPost(res.data) // Which will change `posts`
   })
}, [posts]) // this will trigger useEffect and It goes infinite loop

每次
posts
更改时,都会调用这个useffects,在useffect中,您正在更改posts值,因此进入了一个递归循环

  useEffect(() => {
    axios.get('http://localhost:5000/posts')
        .then(res => {
            setPost(res.data)
        })
    }, [posts])
如果希望只调用一次,则应保留空数组,以便在装入组件时只调用一次

  useEffect(() => {
    axios.get('http://localhost:5000/posts')
        .then(res => {
            setPost(res.data)
        })
    }, [])

添加新帖子时是否要重新渲染?此处不需要使用useEffect。您可以只更新状态。@malong11是的!就像twitter@RunSmeagolRun什么意思?所有的帖子都应该在页面加载后立即显示,这就是我使用useEffect@RunSmeagolRun是的,你不需要在这里使用状态。添加新帖子后,只需发出get请求,并更新它应该重新呈现的状态,因为状态是更新的。我说这对我来说不是一个解决方案,因为我需要在创建新帖子时更新页面,并将括号留空,避免发生这种情况。你刚刚更改了你的问题!,你之前没有要求这样做。我说这对我来说不是一个解决方案,因为我需要在创建新帖子时更新页面,并将括号留空以避免发生这种情况
  useEffect(() => {
    axios.get('http://localhost:5000/posts')
        .then(res => {
            setPost(res.data)
        })
    }, [])