You need to enable JavaScript to run this app. 如何将selectedCountry.capital正确传入axios天气查询请求
优惠活动
大模型
产品
解决方案
定价
更多

如何将selectedCountry.capital正确传入axios天气查询请求

问题原因

你的天气查询useEffect的依赖数组是空值[],按照React的useEffect执行规则,这个请求只会在组件首次渲染完成后触发一次,此时selectedCountry还是初始的空字符串,自然读不到capital属性,所以输出undefined。

修复方案

步骤1:调整selectedCountry初始值

把selectedCountry的初始值改为null,后续判断逻辑更清晰:

const [selectedCountry, setSelectedCountry] = useState(null)

步骤2:重写天气查询的useEffect

将selectedCountry加入依赖数组,同时加前置判断,只有选中国家有有效首都时才发起请求:

useEffect(() => {
  // 选中国家为空/无首都字段时,直接终止执行,避免无效请求
  if (!selectedCountry?.capital) return

  axios
    .get(
      `http://api.weatherstack.com/current?access_key=b51dfd70b0b2ccf136a0d7352876661c&query=${selectedCountry.capital}`
    )
    .then(res =>{
      console.log(res.data)
      console.log("capital"+selectedCountry.capital)
      setWeather(res.data.current)
    })
    .catch(err => console.error('天气请求失败', err))
}, [selectedCountry]) // 依赖设置为selectedCountry,值变化就自动重新触发请求

步骤3:补全单条筛选结果的选中逻辑

你当前只有点击show按钮时才会设置selectedCountry,当搜索筛选结果只剩1个国家直接展示时,需要同步设置选中的国家,才会触发天气查询:
修改showCountries中筛选结果为1的分支代码:

if (filteredCountries.length === 1) {
  const country = filteredCountries[0]
  // 避免重复赋值触发不必要的重渲染
  if (selectedCountry?.alpha2Code !== country.alpha2Code) {
    setSelectedCountry(country)
  }
  return (
    <p key={country.alpha2Code}>
      <p>Capital: {country.capital}.</p>
      <p> Population: {country.population} </p> 
      <h3>languages</h3>
      {country.languages.map(language => <li key={language.name}>{language.name}</li>)}
      <p><img src={country.flag} style={{ width: '200px'}}/></p>
      {/* 可在此处添加天气信息展示代码,示例:
      {weather && (
        <div>
          <h3>首都天气</h3>
          <p>温度:{weather.temperature}℃</p>
          <p>天气状况:{weather.weather_descriptions?.[0] || '无数据'}</p>
          <img src={weather.weather_icons?.[0]} alt="天气图标" />
        </div>
      )} */}
    </p>
  )
}

步骤4:修改搜索事件的重置逻辑

把searchHandler里清空selectedCountry的逻辑和初始值统一:

const searchHandler = (e) => {
  setSelectedCountry(null);
  setSearchFilter(e.target.value)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 00:06:03