首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用搜索值进入Url React Native

使用搜索值进入Url React Native
EN

Stack Overflow用户
提问于 2021-04-13 11:06:59
回答 2查看 20关注 0票数 0

我是一个新手,我正在尝试使用搜索栏来查找一个城市,并使用它作为网址的输入,但不幸的是,似乎没有及时触发,我猜由于useEffect,你能帮我吗?从url中,我希望获得不同城市的纬度和经度值,以便稍后在API中使用它。它适用于美国和墨西哥的城市。

代码语言:javascript
复制
import React, { useEffect, useState, useContext } from 'react';
import { FlatList, Text, View } from 'react-native';
import { Searchbar } from 'react-native-paper';
import MaterialCommunityIcon from 'react-native-vector-icons/MaterialCommunityIcons';

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [city_data, setCity_data] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [resultSearch, setResultSearch] = useState('');

  const onChangeSearch = (query) => setSearchQuery(query);
  

  let place = `https://search.reservamos.mx/api/v2/places?q=${resultSearch}`;
  
  console.log(place);

  useEffect(() => {
    fetch(place)
      .then((response) => response.json())
      .then((json) => {
        // city_data: [name of city, latitude, longitude]
        setCity_data([
          json['0'].city_name,
          json['0'].state,
          json['0'].lat,
          json['0'].long,
        ]);
      })
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  let latit = city_data[2];
  let longit = city_data[3];

  console.log(resultSearch)

  const search = () => {
    return (
      <Searchbar
        placeholder="Search"
        onChangeText={onChangeSearch}
        value={searchQuery}
        icon={() => <MaterialCommunityIcon name="map-search" size={25} />}
        onSubmitEditing={() => setResultSearch(searchQuery)}
      />
    );
  };

  return (
    <View style={{ flex: 0, padding: 24 }}>
      {isLoading ? (
        <Text>Loading...</Text>
      ) : (
        <View
          style={{
            flex: 1,
            flexDirection: 'column',
            justifyContent: 'space-between',
          }}>
          <View>{search()}</View>
          <Text style={{ fontSize: 18, color: 'green', textAlign: 'center' }}>
            The latitude of {city_data[0]}, {city_data[1]} is: {city_data[2]} {resultSearch}
          </Text>
        </View>
      )}
    </View>
  );
};
EN

回答 2

Stack Overflow用户

发布于 2021-04-13 12:19:50

您已经提供了一个空数组作为useEffect的依赖项列表。这意味着useEffect只会在挂载时调用一次的fetch API

这里您想要的是在搜索查询更改时调用fetch API。因此,将place添加到列表中将解决您的问题。

代码语言:javascript
复制
useEffect(() => {

   (...)

}, [place]); // dependency-list
票数 0
EN

Stack Overflow用户

发布于 2021-04-13 13:35:06

你不需要额外的状态来存储搜索查询...

此外,您的fetch未正确使用。

我已经纠正了它,它应该工作得很好。

如果你在这方面有任何错误,请告诉我。

代码语言:javascript
复制
import React, { useEffect, useState, useContext } from "react";
import { FlatList, Text, View } from "react-native";
import { Searchbar } from "react-native-paper";
import MaterialCommunityIcon from "react-native-vector-icons/MaterialCommunityIcons";

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [city_data, setCity_data] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");

  const GetSearchResults = async () => {
    try {
      let place = `https://search.reservamos.mx/api/v2/places?q=${searchQuery}`;
      await fetch(place)
        .then((response) => response.json())
        .then((json) => {
          // city_data: [name of city, latitude, longitude]
          setCity_data([
            json["0"].city_name,
            json["0"].state,
            json["0"].lat,
            json["0"].long,
          ]);
        })
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));
    } catch (error) {
      // log errors here if any
    }
  };

  const search = () => (
    <Searchbar
      placeholder="Search"
      onChangeText={(query) => setSearchQuery(query)}
      value={searchQuery}
      icon={() => <MaterialCommunityIcon name="map-search" size={25} />}
      onSubmitEditing={() => GetSearchResults()}
    />
  );

  return (
    <View style={{ flex: 0, padding: 24 }}>
      {isLoading ? (
        <Text>Loading...</Text>
      ) : (
        <View
          style={{
            flex: 1,
            flexDirection: "column",
            justifyContent: "space-between",
          }}
        >
          <View>{search()}</View>
          <Text style={{ fontSize: 18, color: "green", textAlign: "center" }}>
            The latitude of {city_data[0]}, {city_data[1]} is: {city_data[2]}
            {searchQuery}
          </Text>
        </View>
      )}
    </View>
  );
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67068206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档