首页 > 解决方案 > 如何在 redux 中获得以前的状态?

问题描述

我在使用 react 和 redux 制作简单的天气应用程序时遇到了麻烦。

我有两个减速器。一种用于将数据添加到数组中,另一种用于使用 find 方法从数组中删除数据。

这是代码:

// actions

// fetching weather api 

export const fetchWeather = term => {
  return async dispatch => {
    const res = await api.get(
      `/data/2.5/weather?q=${term}&APPID=132123123132`
    );
    dispatch({ type: "FETCH_WEATHER", payload: res.data });
  };
};

// delete a list that matches the selected id

export const listDelete = id => {
  return {
    type: "LIST_DELETE",
    paylod: id
  };
};

// reducers 

// reducer that put a new data into an array

const reducerIndex = (state = [], action) => {
  switch (action.type) {
    case "FETCH_WEATHER":
      return [...state, action.payload];
    default:
      return state;
  }
};

// reducer that deleting the data that id selected 

const reducerIndexDel = (state = [], action) => {
  switch (action.type) {
    case "LIST_DELETE":
      return state.find(city => city.id !== action.payload);
    default:
      return state;
  }
};

export default combineReducers({
  reducerIndex,
  reducerIndexDel
});

您可能知道,浏览器给我一个错误,说“给定操作“LIST_DELETE”,reducer“reducerIndexDel”返回未定义。

我能够获取我想要的数据,但是我怎样才能让 reducerIndexDel 可以识别以前的状态?

标签: reactjsredux

解决方案


仅用于filter获取不包含带有 id 的城市的状态。

return state.filter(city => city.id !== action.payload)

推荐阅读