我正在我的react原生应用程序中测试google maps autocomplete API。我有一个简单的文本输入字段,它接受一个搜索词,并基于该字段,应用程序从上述API中获取数据。我已经使用redux更新了应用程序中的位置状态。
但添加redux后,我不能在文本输入中键入任何内容,它是工作正常早些时候。我没有看到任何错误,所以我对如何解决无能为力。我已附上相关代码。帮助将不胜感激。
应用程序js
const store = createStore(reducers, compose(applyMiddleware(thunk)));
const App = () => {
return (
<Provider store={store}>
<StatusBar barStyle="dark-content"/>
<SearchScreen/>
</Provider>
);
};
export default App;
减速器.js
第一个
搜索屏幕.js
const SearchScreen = () => {
const [from, setFrom] = useState("");
const dispatch = useDispatch();
const handleFrom = (str) => {
setFrom(str);
if (from.length >= 5)
dispatch(getLocations(from))
}
return (
<SafeAreaView>
<View style={styles.container}>
<TextInput
style={styles.textInput}
placeholder="from"
value={from}
onChangeText={(str) => handleFrom(str)}/>
<Text>{from}</Text>
</View>
</SafeAreaView>
)
};
export default SearchScreen;
获取位置
export const getLocations = (searchTerm) => async (dispatch) => {
try {
const {response} = await api.fetchLocations(searchTerm);
console.log(`response: ${JSON.stringify(response)}`);
// dispatch({type: actionTypes.FETCH_LOCATIONS, payload: response?.predictions});
} catch (e) {
console.error(e);
}
}
API
const API = axios.create({
baseURL: 'https://google-maps-autocomplete-plus.p.rapidapi.com/autocomplete'
});
API.interceptors.request.use((req) => {
req.headers = {
'X-RapidAPI-Key': 'API-KEY',
'X-RapidAPI-Host': 'google-maps-autocomplete-plus.p.rapidapi.com'
};
return req;
});
export const fetchLocations = (query) => API.get(`?query=${query}&limit=5`);
1条答案
按热度按时间mwyxok5s1#
async
函数总是返回一个Promise
。因此,在将它传递给disptach
之前,请等待它有一个值。第一个