简体   繁体   English

React Hook的状态未更新

[英]React Hook's state not getting updated

I've built a React Hook as follows: 我已经建立了一个React Hook,如下所示:

const Index = (props) => {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    const getPosts = async () => {
      const posts = await getPostFromWebService()
      for (let i of posts) {
        setPosts([ ...posts, i ])
      }
    }

    getPosts()
  }, [])

  // ... remaining code
}

But even if the web service returns 5 posts, only the last posts is getting updated in the posts state. 但是,即使Web服务返回5个帖子,在posts状态下,只有最新的帖子正在更新。 Hence it only receives one post in it, instead of 5. 因此,它只收到一个帖子,而不是5。

What am I doing wrong here? 我在这里做错了什么?

It sounds like you want something like this. 听起来您想要这样的东西。 Here we would have the useEffect listen for any changes in postCount so that we can trigger your logic to fetch more posts. 在这里,我们将让useEffect监听postCount中的任何更改,以便我们可以触发您的逻辑来获取更多帖子。

const Index = (props) => {
  const [posts, setPosts] = useState([])
  const [postCount, setPostCount] = useState(0)

  useEffect(() => {
    const getPosts = async () => {
      const newPosts= await getPostFromWebService()

      setPosts([...posts, newPosts])
    }
  }, [postCount])

  return(
    <div>
       <button onClick={() => setPostCount(postCount + 5)}>Get more posts</button>
    </div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM