我目前正试图传入一个位置进行正向地理编码,但不明白为什么我的调用似乎触发了一个无限循环。
我试图使用地图传递位置,然后在代码的其他地方使用API的响应。
这是我的数据提供商。。。
import React, {
useEffect,
useState
} from "react"
export const GeoCodeContext = React.createContext()
export const GeoCodeProvider = (props) => {
const [latLong, setLatLong] = useState([])
const getLatLong = (location) => {
return fetch(`https://api.opencagedata.com/geocode/v1/json?q=${location}&key=MYKEY&limit=1`)
.then(res => res.json())
.then(setLatLong)
}
return (
<GeoCodeContext.Provider value={{latLong,getLatLong}}>
{props.children}
</GeoCodeContext.Provider>
)
}
这里是函数被称为的地方
import React, { useContext } from "react"
import {GeoCodeContext} from "./GeoCodeProvider"
import {LogContext} from "../divelog/DiveLogProvider"
export const MapRender = () =>{
const {diveLogs} = useContext(LogContext)
const {latLong, getLatLong} = useContext(GeoCodeContext)
diveLogs.map(dl =>{
//getLatLong(dl.location)
//console.log(latLong) -- returns an endless log of api calls
})
return <h2>GeoCode Render</h2>
}
每次MapRender
组件渲染时,它会为每个潜水日志调用getLatLong
一次。
getLatLong
最终触发对setLatLong
的调用。。。
导致CCD_ 5重新渲染。。。
这导致CCD_ 6(除其他外(重新渲染。。。
然后我们回到循环的开始。
考虑将MapRender
对getLatLong
的调用封装在对useEffect
钩子的调用中,以避免每次渲染都触发它。