1

我在使用 google-maps api 和来自 rapidapi 的另一个 api 时遇到了这个错误。

首先这是有效的代码:

API -> index.js

import axios from "axios";

const URL =
  "https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary";
// code snippet from "https://rapidapi.com/apidojo/api/travel-advisor/"

const options = {
  params: {
    // bl_latitude: sw.lat,
    // bl_longitude: sw.lng,
    // tr_longitude: ne.lng,
    // tr_latitude: ne.lat,
    bl_latitude: "11.847676",
    tr_latitude: "12.838442",
    bl_longitude: "109.095887",
    tr_longitude: "109.149359",
  },
  headers: {
    "x-rapidapi-host": "travel-advisor.p.rapidapi.com",
    "x-rapidapi-key": "key",
  },
};

export const getPlacesData = async () => {
  try {
    const {
      data: { data },
    } = await axios.get(URL, options);

    return data;
  } catch (error) {
    console.log(error);
  }
};

App.js(只给出区别)

const [bounds, setBounds] = useState(null);

const [places, setPlaces] = useState([]);

useEffect(() => {
    getPlacesData().then((data) => {
      // console.log(data);
      setPlaces(data);
    });
  }, []);

给出错误的代码:

API -> index.js

import axios from "axios";

const URL =
  "https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary";
// code snippet from "https://rapidapi.com/apidojo/api/travel-advisor/"

export const getPlacesData = async (sw, ne) => {
  try {
    const {
      data: { data },
    } = await axios.get(URL, {
      params: {
        bl_latitude: sw.lat,
        bl_longitude: sw.lng,
        tr_longitude: ne.lng,
        tr_latitude: ne.lat,
        // bl_latitude: "11.847676",
        // tr_latitude: "12.838442",
        // bl_longitude: "109.095887",
        // tr_longitude: "109.149359",
      },
      headers: {
        "x-rapidapi-host": "travel-advisor.p.rapidapi.com",
        "x-rapidapi-key": "key",
      },
    });

    return data;
  } catch (error) {
    console.log(error);
  }
};

应用程序.js

useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      ({ coords: { latitude, longitude } }) => {
        setCoordinates({ lat: latitude, lng: longitude });
      }
    );
  }, []);
  // comment: 1

  useEffect(() => {
    getPlacesData(bounds.sw, bounds.ne).then((data) => {
      console.log(data);
      setPlaces(data);
    });
  }, [coordinates, bounds]);

就在此更改之后,它开始出现此错误

我已经尝试了我的最佳水平,但我无法找到代码有什么问题。我用 git 可以看到差异。

4

2 回答 2

2

我遇到了同样的问题。您需要传递一个空对象而不是“null”

const [bounds, setBounds] = useState(null);

这是您当前的代码 ^

const [bounds, setBounds] = useState({});

这将使您的代码工作^

于 2021-10-04T03:13:18.663 回答
-1

你的代码有点不清楚,如果你用尽可能少的代码更简洁地提供你的问题,我可以提供帮助。

但是我在这里可以说的一件事是您将bounds变量声明为null没有属性,那么您如何访问 的sw属性,bounds因为它根本不可用。

此外,您没有使用setBounds方法来设置bounds变量。我错过了什么吗?尝试这样的事情:

const [bounds, setBounds] = useState({ sw: 0, ne: 0});

于 2021-09-20T09:22:58.570 回答