【问题标题】:How can I get a previous state in redux?如何在 redux 中获得以前的状态?
【发布时间】:2019-01-28 07:21:09
【问题描述】:

我在使用 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 可以识别以前的状态?

【问题讨论】:

标签: reactjs redux


【解决方案1】:

我认为你在listDelete 函数中写错了 - “payload”。

您正在尝试访问action.payload,但它写在paylod 那里正在运行。

【讨论】:

  • 正是...因为那个小“a”我浪费了几个小时...并添加了一些更改来解决问题。谢谢你:)
【解决方案2】:

只需使用filter 即可获取不包含id 城市的州。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2021-08-17
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多