[英]How do I get data from Axios and return it from a Function Component in React?
I'm trying to get the id from the URL, so I can get a specific post from the API, in order to return it.我正在尝试从 URL 获取 id,因此我可以从 API 获取特定帖子,以便返回它。 I can't use Class Component to do so, because useParams only works with functions.我不能使用 Class 组件来执行此操作,因为 useParams 仅适用于函数。 I try to put the data inside the variable post, but it also didn't work.我尝试将数据放入变量 post 中,但它也不起作用。
import { useParams } from "react-router-dom";
import axios from "axios";
const Post = () => {
let params = useParams();
let post = null;
axios.get('https://jsonplaceholder.typicode.com/posts/' + params.post_id)
.then(res => {
post = res.data ? (
<div>
<h4>{res.data.title}</h4>
<p>{res.data.body}</p>
</div>
) : (
<div>Loading post...</div>
);
});
return (
<div>{post}</div>
)
}
export default Post
Dynamic data, like a request with axios
should be done within a useEffect
hook.动态数据,例如带有axios
的请求,应该在useEffect
挂钩中完成。 With the dependencies array empty []
it provides that the request in the useEffect
hook will only happen the first render, but not the following after.依赖项数组为空[]
它提供了useEffect
钩子中的请求只会在第一次渲染时发生,但不会在之后发生。
When the response comes in, save the result in a state.收到响应后,将结果保存在 state 中。 Render the proper data based on the value of the state.根据 state 的值呈现正确的数据。
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/' + params.post_id)
.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
You should use useEffect
and useState
hooks in this way您应该以这种方式使用useEffect
和useState
挂钩
import { useEffect, useState } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
import "./App.css";
function App() {
let params = useParams();
const [postState, setPostState] = useState({ data: {}, loading: false });
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/posts/"+ params.post_id).then((res) => {
if (res.data) {
setPostState((s) => ({ ...s, data: res.data }));
} else {
setPostState((s) => ({ ...s, loading: true }));
}
});
}, []);
const { data, loading } = postState;
return (
<>
{data && !loading ? (
<div>
<h4>{data.title}</h4>
<p>{data.body}</p>
</div>
) : (
<div>Loading post...</div>
)}
</>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.