Redux在一个对象数组中创建另一个对象,“类型错误:无法读取未定义的属性(阅读'push')”

monwx1rj  于 2023-06-23  发布在  其他
关注(0)|答案(2)|浏览(96)

我用React来创造一个世界。然后,我使用redux将世界保存为全局状态,以便将一个国家添加到世界上。然后,我使用该国家数据在国家对象内部创建一个城市。我遇到的问题是,我得到一个错误时,试图添加一个城市后,立即创建一个国家。这个国家在redux devtools中出现了。如果我重新加载页面,我可以创建一个城市分配给该国家没有问题。
Redux切片

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);
  }

我在控制台记录了传入切片的数据。我已经在控制台记录了切片中的数据,并检查了redux开发工具。

qzwqbdag

qzwqbdag1#

我必须在最初创建的国家中添加一个空的城市数组

if (response.ok) {
    const createdCountry = await response.json();
    createdCountry.cities = [];
}
qf9go6mv

qf9go6mv2#

state.createdWorld.countries[countryIndex].cites是未定义的,所以没有push元素的数组。在reducer的情况下,首先通过搜索州来获取匹配的国家,然后检查是否存在cities数组,并在必要时创建它。

addCityToCreatedWorld: (state, action) => {
  const { countryPk, newCity } = action.payload;

  const country = state.createdWorld.countries.find(
    (country) => country.pk === countryPk
  );

  if (country) {
    if (!country.cities) {
      country.cities = [];
    }

    country.cities.push(newCity);
  }
},

最好是在 its reducer case中将country添加到state时添加cities数组。
示例:

addCountryToCreatedWorld: (state, action) => {
  const { country } = action.payload;

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

  state.createdWorld.countries.find(
    (country) => country.pk === countryPk
  )?.cities.push(newCity);
},

相关问题