【问题标题】:Axios get request returns 404 when passed url path parameteraxios get请求传url路径参数时返回404
【发布时间】: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


    【解决方案1】:

    请试试这个

    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>
    );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2021-08-08
      • 2021-02-03
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多