以下代码(为简洁起见删除了其中的某些部分)正在运行:
function AddressInputList({
isOpen,
inputValue,
highlightedIndex,
getItemProps,
getMenuProps
}: AutocompleteInputListProps) {
const [items, setItems] = useState<MarkerPoint[]>([])
const api = 'XXXX'
const fetchURL = `https://api.opencagedata.com/geocode/v1/json?key=${api}&q=${inputValue}&limit=5&pretty=1`
useEffect(() => {
async function fetchData() {
if (inputValue !== null && inputValue.length > 1) {
try {
const request = await axios.get(fetchURL)
const items = request.data.results.map((res: any) => {
return {
lat: res.geometry.lat,
lng: res.geometry.lng,
address: res.formatted
}
})
setItems(items)
} catch (error) {
console.error(error)
}
}
}
fetchData()
}, [inputValue])
return (/*Code cut out*/)
}
我现在想做的是重构代码,让它更精简。因此,我将创建一个utility.ts-file,其中包含 -function fetchData,随后我想将fetchData-function 导入初始AddressInputList-function:
实用程序.ts:
export async function fetchData(inputValue: string, fetchURL: string) {
if (inputValue !== null && inputValue.length > 1) {
try {
const request = await axios.get(fetchURL)
const items = request.data.results.map((res: any) => {
return {
lat: res.geometry.lat,
lng: res.geometry.lng,
address: res.formatted
}
})
setItems(items)
} catch (error) {
console.error(error)
}
}
}
现在我的问题是我不知道如何使 useState-hooksetItems在utility.ts. 我在某处读到可以做到这一点props,但我不确定这会是什么样子。一个简短的例子将不胜感激!
阿波罗的战车
MM们
郎朗坤
随时随地看视频慕课网APP
相关分类