You need to enable JavaScript to run this app. React+TypeScript中如何正确结合async/await使用Array.filter
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中如何正确结合async/await使用Array.filter

核心问题定位

你遇到的过滤失效问题,和filter是否需要改成异步没有关系,本质是两个逻辑的执行时序错位 + React Hooks 闭包陷阱导致的:

  • 两个useEffect都是空依赖,组件挂载时会并行触发,根本不会按照你预想的“先拉货币、再拉国家”的顺序执行
  • 第二个触发国家拉取的effect跑的时候,currencies还是初始的空对象{},循环遍历空对象时根本匹配不到任何货币编码,自然过滤结果为空,countries状态也就一直是空
  • 就算后续currencies从服务器加载完成、状态更新,因为第二个effect没有把currencies作为依赖,也不会重新触发国家数据的拉取和过滤逻辑
正确实现方案

有两种可落地的改法,从根源解决时序问题:

方案1:合并串行请求逻辑(推荐,无重复请求风险)

把两个接口请求放在同一个async流程里,严格按照“先拿货币列表、再拉国家数据做过滤”的顺序执行,从流程上避免时序错位:

const App = () => {
  const [countries, setCountries] = useState<Array<CountriesProps>>([])
  const [currencies, setCurrencies] = useState<Currencies>({})
  
  useEffect(() => {
    const initAppData = async () => {
      try {
        // 第一步:先获取支持的货币列表
        const currencyRes = await axios.get('https://api.frankfurter.app/currencies')
        const loadedCurrencies = currencyRes.data as Currencies
        setCurrencies(loadedCurrencies)

        // 第二步:拿到货币编码列表后,再拉取全量国家数据
        const countryRes = await axios.get('https://restcountries.eu/rest/v2/all')
        const allCountries = countryRes.data as Array<CountriesProps>
        const validCurrencyCodes = Object.keys(loadedCurrencies)

        // 基于已加载的货币列表做过滤,无闭包值过期问题
        const filteredCountries = allCountries.filter(country => 
          country.currencies[0]?.code && validCurrencyCodes.includes(country.currencies[0].code)
        )
        setCountries(filteredCountries)
      } catch (err) {
        console.log('数据加载失败', err)
      }
    }

    initAppData()
  }, [])

  return (
    // 组件渲染逻辑
  )
}

方案2:拆分独立逻辑 + 修正effect依赖

如果一定要把货币列表和国家数据的请求拆成独立模块,只需要把触发国家过滤的effect的依赖补上,等currencies加载完成后再自动触发过滤流程:

const App = () => {
  const [countries, setCountries] = useState<Array<CountriesProps>>([])
  const [currencies, setCurrencies] = useState<Currencies>({})
  
  // 第一个effect:仅负责拉取货币列表
  useEffect(() => {
    axios
      .get('https://api.frankfurter.app/currencies')
      .then(res => setCurrencies(res.data))
      .catch(err => console.log(err))
  }, [])

  // 第二个effect:依赖currencies状态,等值更新后再执行过滤
  useEffect(() => {
    // 货币列表未加载完成时直接跳过,避免空对象过滤
    if (Object.keys(currencies).length === 0) return

    const loadFilteredCountries = async () => {
      const { data } = await axios.get('https://restcountries.eu/rest/v2/all')
      const validCodes = Object.keys(currencies)
      const filtered = (data as Array<CountriesProps>).filter(
        country => country.currencies[0]?.code && validCodes.includes(country.currencies[0].code)
      )
      setCountries(filtered)
    }

    loadFilteredCountries()
  }, [currencies]) // 关键:补上currencies作为依赖

  return (
    // 组件渲染逻辑
  )
}
常见认知误区澄清
  • 不需要把filter改成异步形式:filter是纯同步的数组遍历方法,本身不存在异步执行的需求,之前的过滤失效和filter的执行机制完全无关
  • 空依赖的effect不能直接引用后续会更新的state:空依赖effect只会在组件挂载时执行一次,捕获的是挂载时刻的初始state,就算后续state更新了,effect内部拿到的还是旧的闭包值,这是React Hooks最常见的闭包陷阱
  • 原代码的filter遍历写法可读性差,用Object.keys(currencies)生成合法货币编码集合,再通过includes做匹配的写法,比嵌套for循环的执行效率更高,也不容易出现逻辑漏洞

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 10:15:07