首页 > 解决方案 > React - 如何正确进行 API 调用并传递结果以进行进一步过滤?

问题描述

我为我的应用程序使用天气 API。这个想法是从 API 中获取一次作为数组的数据,然后将其传递给进一步处理。我的 App.js 文件如下所示:

import { useState, useEffect } from "react";
import Search from "./components/Search";
import axios from "axios";

function App() {
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
      setCountries(response.data);
    });
  }, []);

  return (
    <div>
      <Search countriesList={countries} />
    </div>
  );
}
export default App;

Search 组件包括一个文本输入字段,传入的数组将根据该字段进行过滤和动态显示。但是,不调用负责过滤的函数。以下是搜索组件的内容:

import { useState } from "react";
import Country from "./Country";

const Search = ({ countriesList }) => {
  const [name, setName] = useState("");

  console.log(countriesList);
  console.log("countries received");
  const filterCountries = (singleCountry, nameFilter) => {
    console.log("hello");
    console.log(singleCountry);
    if (singleCountry.name.toLowerCase().includes(nameFilter.toLowerCase())) {
      return singleCountry;
    }
  };

  const countryRender = (showButtonCondition, showWeatherCondition) => {
    return (
      <div>
        {countriesList
          .filter((country) => filterCountries(country, name))
          .map((filteredCountry) => (
            <Country
              key={filteredCountry.alpha3Code}
              showButton={showButtonCondition}
              showWeather={showWeatherCondition}
              countryId={filteredCountry.alpha3Code}
              countryName={filteredCountry.name}
              countryCapital={filteredCountry.capital}
              countryPopulation={filteredCountry.population}
              countryLanguages={filteredCountry.languages}
              countryFlag={filteredCountry.flag}
            />
          ))}
      </div>
    );
  };

  const nameChangeHandler = (event) => {
    console.log(event.target.value);
    setName(event.target.value);
  };

  return (
    <div>
      search: <input value={name} onChange={nameChangeHandler} />
      <div>
        {countriesList.length > 10 || countriesList.length === 0 ? (
          <div>Too many countres, specify another filter</div>
        ) : (
          <></>
        )}
        {countriesList.length === 1 ? countryRender(false, true) : <></>}
        {countriesList.length > 1 && countriesList.length < 10 ? (
          countryRender(true, false)
        ) : (
          <></>
        )}
      </div>
    </div>
  );
};    
export default Search;

我想问题是名称(用户输入)的变化状态导致整个搜索组件重新渲染并重新获得完整的数组,但是如何克服它呢?React.memo() 方法在这里似乎并不适用,因为文档明确指出它不应该用于防止组件重新渲染。

标签: javascriptreactjsaxiosreact-hooks

解决方案


你从来没有真正打电话countryRender(true, false)countriesList.length > 1 && countriesList.length < 10它仅在其长度为 250时才被调用。


推荐阅读