You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Axios GET请求传路径参数返回404:params.id为何为undefined

为什么Axios请求中params.id变成undefined?

我有一个名为PostDetails的React组件,代码如下:

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;

自定义hook 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请求错误:

GET https://jsonplaceholder.typicode.com/posts/undefined 404

我尝试将URL格式改为:

https://jsonplaceholder.typicode.com/posts/${id}

但仍然出现相同错误。请问为何调用Axios请求时params.id会变成undefined?我哪里出错了?


问题原因及解决方案

1. useFetching未传递参数给回调函数

你的useFetching中定义的fetching函数调用callback()时,没有把外部传入的参数传递进去。当你调用fetchPostById(params.id)时,params.id确实被传入了fetching,但fetching并没有把这个参数传给你的异步回调,导致回调里的id是undefined,最终请求URL中的id也变成undefined。

修改useFetching的代码,让fetching接收并传递参数:

export const useFetching = (callback) => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // 接收任意数量的参数并传递给回调
  const fetching = async (...args) => {
    try {
      setIsLoading(true);
      await callback(...args);
    } catch (e) {
      setError(e.message);
    } finally {
      setIsLoading(false);
    }
  }

  return [fetching, isLoading, error];
}

2. useEffect依赖数组缺失

你的useEffect依赖数组为空,只会在组件挂载时执行一次。如果路由参数params.id后续发生变化(比如从/posts/1跳转到/posts/2),useEffect不会重新触发请求,还可能导致使用旧的参数值。

更新useEffect的依赖数组,加入params.id:

useEffect(() => {
  fetchPostById(params.id)
}, [params.id]) // 添加params.id作为依赖

额外检查

确认你的路由配置正确定义了:id参数,比如:

<Route path="/posts/:id" element={<PostDetails />} />

这样修改后,参数就能正确传递到Axios请求中,不会出现undefined的情况了。


内容的提问来源于stack exchange,提问作者user9695260

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:35:23