Javascript React/Redux警报最佳实践
我是redux新手,我正在使用redux重建一个相当复杂的reactjs应用程序 我认为为通知构建一个“特性”是有意义的,它将有一个类似的状态片Javascript React/Redux警报最佳实践,javascript,reactjs,redux,redux-thunk,react-toolbox,Javascript,Reactjs,Redux,Redux Thunk,React Toolbox,我是redux新手,我正在使用redux重建一个相当复杂的reactjs应用程序 我认为为通知构建一个“特性”是有意义的,它将有一个类似的状态片 import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { RootState } from '../../app/store'; export interface NotificationState { show: boolean, status:
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
export interface NotificationState {
show: boolean,
status: 'info' | 'warn' | 'error' | 'success',
title: string,
message: string,
position: 'dash' | 'popover',
}
const initialState: NotificationState = {
show: false,
status: 'info',
title: '',
message: '',
position: 'popover',
};
export const notificationSlice = createSlice({
name: 'notification',
initialState,
reducers: {
show: (state, action: PayloadAction<NotificationState>) => {
state = action.payload;
},
hide: (state) => {
state.show = false;
},
toggle: (state) => {
state.show = !state.show;
},
},
});
const { actions, reducer } = notificationSlice;
export const { show, hide, toggle } = actions;
export const selectNotification = (state: RootState) => state.notification;
export default reducer;
明显的问题是,你不应该从减速器中调度操作。一般来说,这是一个坏主意,还是有办法通过thunk响应设置
通知
状态?是否有一种“最佳实践”方法来处理这个问题?在这种特殊情况下,我认为您需要改变实现方法
您可以让notifications(通知)切片添加一个侦听任何“已拒绝”操作的extraReducers
案例,并显示基于该操作的通知。我们特别鼓励多个减速器处理一个动作:
extraReducers: (builder) => {
builder
.addCase(fetchBlogPosts.fulfilled, (state, action) => {
state.status = 'idle';
state.entities = action.payload;
})
// hopefully this will apply to any failed / pending request
.addMatcher(isRejectedAction, (state, action) => {
state.error = action.error;
// store.dispatch(show({
// show: true,
// status: 'error',
// title: 'Request Failed',
// message: action.error.message,
// position: 'popover',
// autoHide: false,
// confirm: false,
// }));
})
.addMatcher(isPendingAction, (state, action) => {
state.status = 'loading';
})
}