繁体   English   中英

如何使用 Rest 国家/地区 Api 按名称搜索

[英]How to Search by name using the Rest country Api

当我搜索一个国家时,searchInput useState 工作正常并接收值,问题是它不会立即更新 Dom 中的国家,除非我删除 useEffect 挂钩依赖数组,这会导致太多重新渲染,那么如何我可以在搜索时更新 DOM,这是我的代码。

 const countryUrl = `https://restcountries.com/v2/name`;

 const [searchInput, setSearchInput] = useState<string>("Nigeria");
 const [countryData, setCountryData] = useState<object>([]);

 const fetchCountry = (searchInput: any) => {
    axios
      .get(`${countryUrl}/${searchInput}?fullText=true`)
      .then((res) => setCountryData(res.data[0]))
      .catch((err) => console.log(err));
  };

 useEffect(() => {
    fetchCountry(searchInput);
  }, []);

 const handleSubmit = (e: any) => {
    e.preventDefault();
    fetchWeather(searchInput);
    fetchCountry();
  };
 <form onSubmit={handleSubmit}>
              <input
                onChange={(e) => setSearchInput(e.target.value)}
                placeholder="Enter The Country"
                type="text"
              />
              <button type="submit">{<CiSearch />} </button>
            </form>

searchInput fetchCountry = (searchInput: any) => {中删除 searchInput,它看起来像fetchCountry = () => {

原因是你在 useState 中有 searchInput,所以不需要作为 foo 参数传递

你的 fetchCountry 看起来像

 const fetchCountry = () => { // removed params
    axios
      .get(`${countryUrl}/${searchInput}?fullText=true`)
      .then((res) => setCountryData(res.data[0]))
      .catch((err) => console.log(err));
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM