首页 > 解决方案 > React Redux 存储不会在从状态中删除项目时更新

问题描述

我正在使用如下@reduxjs/toolkit创建reducer a:delete

const slice = createSlice({
  name: "hotels",
  initialState: {
    list: [],
    loading: false,
    lastFetch: null,
  },
  reducers: {
    hotelsRequested: (hotels) => {
      hotels.loading = true;
    },
    hotelsRequestFailed: (hotels) => {
      hotels.loading = false;
    },
    hotelsReceived: (hotels, action) => {
      hotels.list = action.payload;
      hotels.loading = false;
      hotels.lastFetch = Date.now();
    },

    hotelDeleted: (hotels, action) =>
      hotels.list.filter((hotel) => hotel.slug !== action.payload.slug),
  },
});

export const {
  hotelsReceived,
  hotelsRequestFailed,
  hotelsRequested,
  hotelDeleted,
} = slice.actions;
export default slice.reducer;

删除操作如下

export const loadHotels = () => (dispatch, getState) => {
  const { lastFetch } = getState().entities.hotels;
  const diffInMinutes = moment().diff(lastFetch, "minutes");
  if (diffInMinutes < 10) return;
  dispatch(
    hotelApiCallBegan({
      url: hotelUrl,
      onStart: hotelsRequested.type,
      onSuccess: hotelsReceived.type,
      onError: hotelsRequestFailed.type,
    })
  );
};
export const deleteHotel = (slug) =>
  hotelApiCallBegan({
    url: `/hotel/${slug}/delete/`,
    method: "delete",
    onSuccess: hotelDeleted.type,
  });

这是中间件

export const hotelsApi = ({ dispatch }) => (next) => async (action) => {
  if (action.type !== actions.hotelApiCallBegan.type) return next(action);

  const { onStart, onSuccess, onError, url, method, data } = action.payload;

  if (onStart) dispatch({ type: onStart });

  next(action);
  try {
    const response = await axiosInstance.request({
      baseURL,
      url,
      method,
      data,
    });

    //General
    dispatch(actions.hotelApiCallSuccess(response.data));
    //Specific
    if (onSuccess) dispatch({ type: onSuccess, payload: response.data });
  } catch (error) {
    //general error
    dispatch(actions.hotelApiCallFailed(error.message));
    //Specific error
    if (onError) dispatch({ type: onError, payload: error.message });
  }
};

当我点击 ui 上的删除按钮时, onClick={() => this.props.onDelete(hotel.slug)}我可以在 chrome 开发工具的网络选项卡上看到酒店已被删除。但是状态保持不变,直到页面刷新。这里有什么问题?

标签: reactjsreact-redux

解决方案


您需要返回酒店列表:

return hotels.list.filter((hotel) => hotel.slug !== slug);

或者

hotelDeleted: (hotels, action) => hotels.list.filter((hotel) => hotel.slug !== action.payload.slug)

// 更新

要使用 immer(工具包在后台使用),您必须以不同的方式删除它。不是通过使用过滤器。

 hotelDeleted: (hotels, action) => {
  const { slug } = action.payload;
  const index = hotels.list.findIndex((hotel) => hotel.slug !== slug);
  hotels.list.splice(index, 1);
},

推荐阅读