TypeError:无法使用google-maps api和rapidapi读取null的属性(读取'sw')



我在使用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);
}
};

App.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来看看有什么不同

我也有同样的问题。您需要传递一个空对象,而不是"null">

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

这是你当前的代码^

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

这将使你的代码工作^

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

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

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

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

App.js中的getPlacesData添加可选的链接操作符

getPlacesData(bounds?.sw, bounds?.ne)
.then((data) =>{
setPlaces(data);
});

相关内容

最新更新