早上好, 我正在构建这个 Android 应用程序原型,该应用程序应该使用 Here API 的自动完成功能来帮助选择要搜索的位置。
这是我的代码文件:
App.js:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux'
import { store } from './store';
import TabTwoScreens from './screens/TabTwoScreens';
export default function App() {
return (
<Provider store={store}>
<TabTwoScreens />
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
TabTwoScreen(屏幕文件夹内):
import React, { useState } from 'react';
import { Text, View, SafeAreaView, StyleSheet, TouchableWithoutFeedback, Pressable, Keyboard, FlatList, TextInput } from "react-native";
import { Location } from "../types/location";
import { MaterialIcons } from "@expo/vector-icons"
export default function TabTwoScreeen() {
const [input, setInput] = useState<string>();
const [data, setData] = useState<Location[]>();
// updates the input
const onChangeText = async (text: string) => {
setInput(text)
if (text.length === 0) return setData([]);
if (text.length > 2) {
let endpoint = `http://192.168.0.105:4000/api/search?location=${text}&limit=${5}`
const res = await fetch(endpoint);
if (res) {
const data: Location[] = await res.json();
if (data.length > 0) setData(data);
}
}
console.log("get data")
}
const getItemText = (item: Location) => {
let mainText = item.title;
return (
<View style={{ flexDirection: "row", alignItems: "center", padding: 15 }} >
<MaterialIcons
name={item.administrativeAreaType === "city" ? "location-city" : "location-on"}
color={"black"}
size={30}
/>
<View style={{ marginLeft: 10, flexShrink: 1 }}>
<Text style={{ fontWeight: "700" }}>{mainText}</Text>
<Text style={{ fontSize: 12 }}>{item.address.countryName}</Text>
</View >
</View >
)
}
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.label}>Search Location</Text>
<TextInput
placeholder="Find location"
value={input}
onChangeText={onChangeText}
style={styles.input}
/>
<FlatList
data={data}
renderItem={({ item, index }) => (
<Pressable onPress={() => alert("navigate passing" + JSON.stringify(item))}
>
</Pressable>
)}
/>
</View>
</SafeAreaView>
</TouchableWithoutFeedback>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
marginLeft: 12,
marginRight: 12,
},
label: {
marginBottom: 5,
fontSize: 12,
},
input: {
height: 40,
borderWidth: 1,
paddingHorizontal: 10,
borderRadius: 5,
},
});
index.ts(在 src_mine 文件夹内):
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cors from "cors";
import helmet from "helmet";
import axios from "axios";
const app = express()
app.use(cors());
app.use(helmet());
app.get("api/search", async (req, res) => {
try {
const endpoint = `https://autocomplete.search.hereapi.com/v1/autocomplete?apikey=${process.env.HERE_key}&lang=it-IT&limit=${req.query.limit}&q=${req.query.location}`;
const { data } = await axios.get(endpoint);
if (data) return res.send(data);
res.send([]);
} catch (error) {
res.send([]);
}
});
app.use("/", (req, res) => {
res.send("Hello There");
})
const port = process.env.PORT || 4000;
app.listen(port, () => console.log("listening on", port))
最后是 location.ts(在 types 文件夹内):
export type Location = {
title: string;
id: string;
language: string;
resultType: string;
administrativeAreaType?: string;
localityType?: string;
address: {
label: string;
countryCode: string;
countryName: string;
stateCode?: string;
state?: string;
county?: string;
city?: string;
postalCode?: string;
};
highlights: {
title?: { start: number; end: number }[];
address?: {
label?: { start: number; end: number }[];
state?: { start: number; end: number }[];
city?: { start: number; end: number }[];
};
};
};
使用
expo start
命令,我可以在手机上看到研究选项卡,并且可以写入其中。在 TabTwoScreen 组件中,您正在检查
if(res)
,它变为 true 以确定 API 成功或失败(请参阅此处 Fetch API 的行为 https://developer.mozilla.org/en-US/docs/Web /API/Fetch_API/Using_Fetch)。所以它很可能会进入区块并在 await res.json()
处失败。
在继续下一步之前,您应该阅读 res
对象以查看它是否符合预期。
您可以尝试以下操作以更好地了解如何修复错误 -