You need to enable JavaScript to run this app. React天气应用fetch拉取数据刷新为空、热重载正常问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React天气应用fetch拉取数据刷新为空、热重载正常问题求助

问题排查及修复方案

核心问题根因

  • React状态更新是异步的:调用setState后不会立刻更新当前作用域内的状态值,你在请求的then链、Promise.all回调里拿到的永远是当前渲染周期的旧状态值。
  • 依赖项配置错误:useEffect只配置了空依赖数组,仅在组件首次挂载时执行一次,此时异步请求尚未返回,计算出来的locationResults自然是空值。
  • Promise链写法错误:多处回调没有用函数包裹,导致代码提前执行,没有等待异步请求完成。

具体错误点及修复

1. 修正ProfilesProvider的方法

原代码中then(console.log(profiles))会立即执行console.log,不会等待请求和状态更新完成,且没有返回值供Promise.all感知请求结束:

// 修改后的getProfiles
const getProfiles = () => {
  return fetch("http://localhost:8088/profiles")
    .then((res) => res.json())
    .then((theProfiles) => {
      setProfiles(theProfiles)
      return theProfiles // 返回结果让Promise.all能拿到完成信号
    })
}

// 修改后的getCurrentProfile
const getCurrentProfile = () => {
  const id = localStorage.getItem("weathernet_user")
  if (!id) return Promise.resolve({}) // 加本地存储判空,避免无效请求
  return fetch(`http://localhost:8088/profiles/${id}`)
    .then((res) => res.json())
    .then((theProfile) => {
      setCurrentProfile(theProfile)
      return theProfile
    })
}

2. 修正LocationsProvider的addLocation方法

原代码.then(getLocations())会立即执行getLocations,不会等待POST请求完成:

const addLocation = (locationObj) => {
  return fetch("http://localhost:8088/locations", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(locationObj),
  }).then(getLocations) // 去掉括号,传入函数引用,等请求完再执行
}

3. 修正LocationList业务逻辑

删除冗余的本地profile状态,用useMemo计算用户保存的地点列表,避免异步状态更新导致的空值问题:

export const LocationList = () => {
  const { locations, getLocations, deleteLocation } = 
    useContext(LocationContext);
  const { profiles, getProfiles, currentProfile, getCurrentProfile } = 
    useContext(ProfileContext);
  const [city, setCity] = useState("");
  const [result, setResult] = useState({});
  const [isHidden, setIsHidden] = useState(true);
  // 删除冗余的profile state,用useMemo计算按钮列表
  const buttonList = React.useMemo(() => {
    return (currentProfile.savedCityId || []).map((cityId) => {
      return locations.find((location) => location.id === cityId);
    }).filter(Boolean); // 过滤找不到的无效id
  }, [currentProfile, locations]) // 依赖这两个值,更新时自动重新计算

  const history = useHistory();

  useEffect(() => {
    // 删除多余的setCurrentProfile调用
    Promise.all([
      getLocations(),
      getProfiles(),
      getCurrentProfile(),
    ])
  }, []);

  // 后续渲染逻辑直接用buttonList即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 04:00:05