传递url路径参数时,Axios get请求返回404

sh7euo9m  于 2022-09-28  发布在  iOS
关注(0)|答案(2)|浏览(258)

我有一个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”会转换为未定义?我在这里做错了什么?

nwnhqdif

nwnhqdif1#

请试试这个

const PostDetails = () => {
const {id} = useParams();
const [post, setPost] = useState({});
const [fetchPostById, isLoading, error] = useFetching(async (id) => {
   const response = await PostService.getById(id);
   setPost(response.data);
 })

useEffect(() => {
   id && fetchPostById(id)
}, [id])

return (
    <div>
       <h1>Post details page for ID = {params.id}</h1>
       <div>{post.id}. {post.title}</div>
    </div>
);
};
gojuced7

gojuced72#

添加参数。useEffect数组依赖项的id变量:

useEffect(() => {
    fetchPostById(params.id)
}, [params.id])

相关问题