You need to enable JavaScript to run this app. React如何正确调用API并传递返回结果用于后续过滤?
优惠活动
大模型
产品
解决方案
定价
更多

React如何正确调用API并传递返回结果用于后续过滤?

问题根源

你的问题和组件重渲染没有任何关系,真正的原因是你所有的渲染分支判断的都是原始未过滤的国家数组长度,而restcountries接口返回的全量国家总数超过200,所以countriesList.length > 10的判断永远成立,代码只会走到「Too many countres, specify another filter」的分支,根本不会调用countryRender函数,过滤函数自然不会执行。

你之前的猜测完全是错误的:name变化触发组件重渲染是正常的必要行为,只有重渲染才能拿到最新的输入值计算过滤结果,完全不需要用React.memo做处理。


解决方法

先把过滤后的国家数组抽成独立变量,所有渲染条件都基于过滤后的数组长度判断即可。

修改后的Search组件代码:

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

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

  // 抽离过滤逻辑,每次name或countriesList变化时自动更新过滤结果
  const filteredCountries = countriesList.filter(singleCountry => {
    return singleCountry.name.toLowerCase().includes(name.toLowerCase())
  })

  const countryRender = (showButtonCondition, showWeatherCondition) => {
    return (
      <div>
        {filteredCountries.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) => {
    setName(event.target.value);
  };

  return (
    <div>
      search: <input value={name} onChange={nameChangeHandler} />
      <div>
        {/* 所有长度判断改用过滤后的数组 */}
        {filteredCountries.length > 10 || filteredCountries.length === 0 ? (
          <div>Too many countres, specify another filter</div>
        ) : filteredCountries.length === 1 ? (
          countryRender(false, true)
        ) : (
          countryRender(true, false)
        )}
      </div>
    </div>
  );
};    
export default Search;

内容的提问来源于stack exchange,提问作者user9507446

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 04:18:03