【发布时间】:2022-09-28 20:38:27
【问题描述】:
我有一个像这样的 React 组件“PostDetails”:
const PostDetails = () => {
const params = useParams();
const [post, setPost] = useState({});
const [fetchPostById, isLoading, error] = useFetching(async (id) => {
const response = await PostService.getById(id);
setPost(response.data);
})
useEffect(() => {
fetchPostById(params.id)
}, [])
return (
<div>
<h1>Post details page for ID = {params.id}</h1>
<div>{post.id}. {post.title}</div>
</div>
);
};
export default PostDetails;
自定义挂钩 \"useFetching\" 是这样实现的:
export const useFetching = (callback) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(\'\');
const fetching = async () => {
try {
setIsLoading(true);
await callback();
} catch (e) {
setError(e.message);
} finally {
setIsLoading(false);
}
}
return [fetching, isLoading, error];
}
实用程序类 \"PostService\" 是这样实现的:
export default class PostService {
static async getById(id) {
const response = await axios.get(\"https://jsonplaceholder.typicode.com/posts/\" + id);
return response;
};
}
在浏览器控制台中,我收到“GET”请求的错误,如下所示:
获取https://jsonplaceholder.typicode.com/posts/undefined 404
我试图像这样重新格式化我的 URL:
https://jsonplaceholder.typicode.com/posts/${id}但仍然得到同样的错误。
为什么当我调用我的 axios 获取请求时 \"params.id\" 会转换为 undefined?我在这里做错了什么?
标签: reactjs react-hooks axios