reactjs - 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 开发工具的网络选项卡上看到酒店已被删除。但是状态保持不变,直到页面刷新。这里有什么问题?
解决方案
您需要返回酒店列表:
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);
},
推荐阅读
- c# - Bootstrap Modal 将输入参数传递给控制器而不关闭模态
- java - Vaadin:不能强制从线程更新progressBar
- javascript - Socket IO - NodeJS 需要外部脚本吗?
- javascript - 从第一个数组中删除除第一次出现的第二个数组项之外的所有元素
- python - pip 升级后无法安装 numpy
- javascript - 根据给定变量的长度动态创建函数
- python - Python - Argparse:调用帮助参数返回错误
- youtube-api - Youtube Data API V3 - 通过 PHP 代码上传视频显示错误
- perl - 如何在 Perl 中将一系列数字(例如:100 到 200)作为命令行参数传递?
- sql-server - 从包含在“with”子句中的列计算