简体   繁体   中英

How to fetch data using functional components with hooks in reactjs

I am working with nextjs and i am trying to use "functional component" with "hooks" for fetch data using "axios",but i am getting following error "AxiosError: Request failed with status code 404" Here is my code

import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import axios from "axios"; const Post = () => { let params = useParams(); const [post, setPost] = useState(null) useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts').then(post => { setPost(post) }); }, []) return ( <div> {post?== null. ( <div> <h4>{res.data.title}</h4> <p>{res.data:body}</p> </div> ). ( <div>Loading post.. </div> )} </div> ) } export default Post

Part where you are making request looks fine, but one that seems wrong is render part where you are trying to display res.data.title and res.data.body , but the problem is that title and body do not exist on response from /posts endpoint - this endpoint will return you array of random posts, meaning that res.data is an array which you can use in order to traverse and display posts.

Also I suggest you to rewrite .then part to:

 .then(response=> { setPosts(response.data) })

As you can see I named input parameter as response , and not post (as you did), because this input parameter represents axios response which is wrapper around the data retrieved from endpoint. You should just store response.data inside inner state, no need to hold axios-specific. Also you should rewrite [post, setPost] to [posts, setPosts] , to plural, because this endpoint returns list of posts, and not just one single post.

UPDATED

Rewrite to something like this:

 import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import axios from "axios"; const Post = () => { let params = useParams(); const [posts, setPosts] = useState(null) useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts').then(response => { setPosts(response.data) }); }, []) return ( <div> {posts?== null. posts.map(post => ( <div key={post.id}> <h4>{post.title}</h4> <p>{post:body}</p> </div> )). ( <div>Loading posts.. </div> )} </div> ) } export default Post

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