使用axios时,在react中未获得API响应

bmvo0sr5  于 2023-03-02  发布在  iOS
关注(0)|答案(3)|浏览(173)

我试图显示信息从一个API使用axios和挂钩useParams,这似乎是一个直接的练习,但它不工作。API工作,这里是代码:

// eslint-plugin-react-hooks
import React, { useEffect, useState } from 'react';
import { NavLink, useParams } from 'react-router-dom';
import axios from 'axios';
import styles from './CarDetails.module.css';
import Sidebar from '../../common/sidebar/Sidebar';

const CarDetails = () => {
  const { id } = useParams();
  const [car, setCar] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    axios
      .get(`https://carrental2.onrender.com/api/v1/cars/${id}`)
      .then((response) => {
        setCar(response.data.car);
        console.log(response.data.car);
        setLoading(false);
      });
  }, [id]);

  const newLocal = <Sidebar />;
  if (loading) {
    return (
      <div className="container-fluid vh-100 v-100 d-flex justify-content-center align-items-center">
        <i className="fa-solid fa-spinner fa-spin fs-1" />
      </div>
    );
  }
  return (
    <>
      {newLocal}
      <h2 className={styles.title}>CAR DETAILS</h2>
      <div className={styles.detailContainer}>
        <div className={styles.car}>
          <img src={car.image} alt={car.model} />
        </div>
        <div className={styles.detail}>
          <h2>{car.model}</h2>
          <div className={styles.carYear}>
            <p>year:</p>
            <p>{car.year}</p>
          </div>
          <div className={styles.price}>
            <p>Price Per Day: </p>
            <p className={styles.priceColor}>
              $
              {car.price}
            </p>
          </div>
          <NavLink to={`/reserve/${id}`} className={styles.btncontainer}>
            <button type="button" className={styles.reservebtn}>
              <i className="fa-solid fa-car-side me-3" />
              Reserve
            </button>
          </NavLink>
        </div>
      </div>
    </>
  );
};
export default CarDetails;

我还没有尝试其他方法,因为我相信这是使用Axios最简单的方法,我哪里搞错了?如果您想尝试API链接,请使用63到69汽车。

jjhzyzn0

jjhzyzn01#

我检查了axios API响应,它没有汽车属性
请将useEffect更改为:

useEffect(() => {
    setLoading(true);
    axios
      .get(`https://carrental2.onrender.com/api/v1/cars/${id}`)
      .then((response) => {
        setCar(response.data);
        console.log(response.data);
        setLoading(false);
      });
  }, [id]);

show result on code sandbox

zwghvu4y

zwghvu4y2#

首先,应该对id进行健全性检查。如果useParams是异步的,则可能未定义。其次,应该在axios承诺中添加一个catch来处理错误。

useEffect(() => {
  if (id) {
    setLoading(true);
    axios
      .get(`https://carrental2.onrender.com/api/v1/cars/${id}`)
      .then((response) => {
        setCar(response.data.car);
        console.log(response.data.car);
        setLoading(false);
      })
      .catch((err) => {
        console.error(err);
      });
  }
}, [id]);
hxzsmxv2

hxzsmxv23#

从axios获取返回一个 Promise< Response >,这意味着它必须是waited。useEffect不支持这一点,我使用一个异步回调函数来帮助使用useEffect钩子内的waited函数。

// fetch data callback function vvv asyncronous
const fetchData = useCallback( async (id) => {
  setLoading(true);
  // await axios get function
  await axios
    .get(`https://carrental2.onrender.com/api/v1/cars/${id}`)
    .then((response) => {
      setCar(response.data);
      console.log(response.data);
      setLoading(false);
    });
}, [])

useEffect(() => {
  
  // call the callback function
  fetchData(id);

        // include the function in the dependencies
}, [id, fetchData]);

相关问题