【发布时间】:2021-10-21 23:51:27
【问题描述】:
- 我正在尝试获取用户的经纬度坐标,然后使用这些坐标在 useEffect() 内部发出搜索请求
-
当
useResults时,location始终为null执行,这就是问题 -
useResults和fetchLocation都单独工作,但我无法将它们链接在一起 - 任何想法都将不胜感激,谢谢
我的代码(我正在尝试做这样的事情)
const [fetchLocation, location, message] = useLocation()
const [fetchResults, searchResults, isSearchError] = useResults()
useEffect(() => {
fetchLocation() // get user longitude and latitude, set longitude and latitude data into "location"
useResults({
location.coords.longitude,
location.coords.latitude }) // feed longitude and latitude data into useResults
}, [])
useResults.js
const useResults = () => {
const [searchResults, setSearchResults] = useState([])
const [isSearchError, setIsSearchError] = useState(false)
const fetchResults = async (
searchTerm,
{ latitude, longitude }
) => {
try {
// get search data
const response = await yelpAPI.get("/search", {
params: {
limit: 50,
term: searchTerm,
latitude,
longitude
}
})
// set search data
setSearchResults(response.data.businesses)
} catch (err) {
console.log(err)
console.log("Something went wrong in useResults.js")
setIsSearchError(true)
}
}
return [fetchResults, searchResults, isSearchError]
}
useLocation.js
const useLocation = () => {
const [location, setLocation] = useState(null)
const [message, setMessage] = useState(
"Fetching user location data"
)
const fetchLocation = async () => {
try {
let { status } =
await Location.requestForegroundPermissionsAsync()
if (status !== "granted") {
setErrorMsg(
"Permission to access location was denied"
)
return
}
// get user location data
let locationData = await Location.getCurrentPositionAsync(
{}
)
setMessage(null)
// set user location data
setLocation(locationData)
} catch (err) {
console.log(err)
setMessage("Fetching user location failed")
}
}
return [fetchLocation, location, message]
}
【问题讨论】:
标签: reactjs react-native react-hooks use-effect