【问题标题】:React / Redux alerting best practicesReact / Redux 警报最佳实践
【发布时间】:2021-08-19 20:38:35
【问题描述】:

我是 redux 新手,我正在使用 redux 重建一个相当复杂的 reactjs 应用程序。

我认为为通知构建一个“功能”是有意义的,该通知将具有类似状态的一部分

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;    

这将控制通知的显示方式、位置、使用的警报颜色等。

但是,现在我开始着手实现,我发现我想根据其他功能的状态显示通知。例如,在我的 blog-posts 功能中,我通过 thunk 从服务器获取数据,我想根据 thunk 的状态设置通知:

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';
        })
}

明显的问题是你不应该从 reducer 中分派动作。一般来说,这只是一个坏主意,还是有办法从 thunk 响应中设置 notification 状态?是否有“最佳实践”方法来处理这个问题?

【问题讨论】:

    标签: javascript reactjs redux redux-thunk react-toolbox


    【解决方案1】:

    在这种特殊情况下,我认为您需要翻转实现方法。

    您可以让通知切片添加一个extraReducers 案例,以侦听任何“被拒绝”操作,并根据该操作显示通知。多个 reducer 处理一个动作是我们特别鼓励的一种模式:

    【讨论】:

    • 太完美了,谢谢。不知道为什么我没有想到!
    猜你喜欢
    • 2022-12-01
    • 2015-06-20
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多