简体   繁体   中英

React Hook's state not getting updated

I've built a React Hook as follows:

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. Hence it only receives one post in it, instead of 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.

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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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