You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux添加城市时报错:Cannot read properties of undefined (reading 'push')

问题:刚创建国家后立即添加城市触发Cannot read properties of undefined (reading 'push')错误

问题场景

用React+Redux构建世界模型,全局状态存储createdWorld,流程是先添加国家,再基于已有国家创建城市:

  • 刚创建完国家就立即添加城市时,触发错误Cannot read properties of undefined (reading 'push'),但Redux DevTools中已能看到该国家
  • 刷新页面后再添加城市则完全正常

相关代码

Redux Slice 处理添加城市的逻辑

addCityToCreatedWorld: (state, action) => {
  const { countryPk, newCity } = action.payload;
  const countryIndex = state.createdWorld.countries.findIndex(
    (country) => country.pk === countryPk
  );
  if (countryIndex >= 0) {
    state.createdWorld.countries[countryIndex].cities.push(newCity);
  }
}

React 组件提交城市的代码

const handleCitySubmit = async (event) => {
  event.preventDefault();

  const data = {};
  data.name = cityName;
  data.picture = cityPicture;
  data.description = cityDescription;
  data.country = countryData.pk;

  let cityUrl = `${process.env.REACT_APP_API_HOST}/api/cities`;
  let cityFetchConfig = {
    method: "post",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
    },
  };

  const response = await fetch(cityUrl, cityFetchConfig);
  if (response.ok) {
    const createdCity = await response.json();
    dispatch(
      addCityToCreatedWorld({
        countryPk: countryData.pk,
        newCity: createdCity,
      })
    );
    setSubmitted(true);
  } else {
    console.error(response);
  }
}

问题原因

刚创建的国家对象没有初始化cities数组——虽然Redux DevTools能看到国家存在,但该国家的cities属性是undefined,调用.push()自然会报错。刷新页面后,国家数据从后端重新获取,后端返回的国家对象会默认包含空的cities数组,所以此时能正常执行.push()。


解决方案

有两种直接有效的修复方式:

1. 添加国家时初始化cities数组

在创建国家的Redux reducer逻辑里,给新添加的国家对象默认加上cities: [],确保国家从创建时就具备该属性:

addCountryToCreatedWorld: (state, action) => {
  const newCountry = {
    ...action.payload,
    cities: [] // 显式初始化空数组
  };
  state.createdWorld.countries.push(newCountry);
}

2. 在添加城市的reducer里做兜底处理

在调用.push()前,先检查cities是否存在,不存在则先初始化为空数组:

addCityToCreatedWorld: (state, action) => {
  const { countryPk, newCity } = action.payload;
  const countryIndex = state.createdWorld.countries.findIndex(
    (country) => country.pk === countryPk
  );
  if (countryIndex >= 0) {
    const country = state.createdWorld.countries[countryIndex];
    // 兜底初始化cities数组
    if (!country.cities) {
      country.cities = [];
    }
    country.cities.push(newCity);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:38:39