2 回答
TA贡献1886条经验 获得超2个赞
只需创建一个自定义挂钩即可为您获取数据。我不建议把这个钩子绑inputValue那么多。此外,.map 格式也不通用。
export function useFetchData(inputValue: string, fetchURL: string) {
const [items,setItems] = useState([]);
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)
}
}
}
}, [inputValue]);
return items;
}
之后你可以像这样使用这个自定义钩子
const items = useFetchData(inputValue, "/api/<endpoint>);
TA贡献1921条经验 获得超9个赞
我想您可以将 setItems 作为回调函数作为参数传递给您的 fetchData 函数。
fetchData(inputValue: string, fetchURL: string, setItems) {
...
}添加回答
举报
