【问题标题】:How can I change state of another reducer from extra reducers add cases如何从额外的减速器添加案例中更改另一个减速器的状态
【发布时间】:2021-10-13 17:14:11
【问题描述】:

我正在尝试创建一个通知组件。 我的通知组件处于根级别,当用户尝试登录时,异步函数的进程会转发给他,即等待完成或拒绝。

问题是我不知道如何从 userSlice 调用通知缩减程序,或者即使这可能是一个好方法。

用户切片

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialUserState = { 
    currentUser:null 
}

export const getUser = createAsyncThunk(
    'user/getUser',
    async (endpoint, data) => {
        return(
            await axios.post(endpoint, data)
            .then(res =>{
                return res.data.user
            })
            .catch(error =>{
                throw Error(error.response.data)
            })
        )
    }
)

const userSlice = createSlice({
    name: 'user',
    initialState: initialUserState,
    reducers:{
        currentUser(state, action){
            state.currentUser = action.payload
        }
    },
    extraReducers: 
        (builder) => {
            builder.addCase(getUser.pending, ()=>{
                console.log("authing")
            })
            builder.addCase(getUser.fulfilled, (state, action)=>{
                state.currentUser = action.payload
                console.log("fulfilled")
            })
            builder.addCase(getUser.rejected, (state, action)=>{
                console.log("failed")
                alert(action.error.message)
            })
        }
})

export const userActions = userSlice.actions;
export default userSlice.reducer;

通知切片

import React from 'react'
import { useSelector } from 'react-redux'

function Notification() {

    const toast = useSelector(state => state.notification)
    console.log(toast)
    return (
        toast.active &&
        <div className="notification" style={{backgroundColor:toast.backgroundColor}} >
            {toast.message}
        </div>
    )
}

export default Notification

我想在调用 userSlice 中的额外减速器之一时更改通知状态

【问题讨论】:

    标签: reactjs redux react-redux reducers redux-toolkit


    【解决方案1】:

    我认为您几乎完全倒退了这一点。您想要的不是“从 userSlice 调用通知缩减程序”,而是在 notificationSlice 中侦听 userSlice 操作。

    我做了以下类似的事情,我认为这对你很有效:

    import { createEntityAdapter, createSlice, isAnyOf } from '@reduxjs/toolkit'
    
    const notificationsAdapter = createEntityAdapter()
    
    const initialState = notificationsAdapter.getInitialState({
      error: null,
      success: null,
    })
    
    const notificationsSlice = createSlice({
      name: 'notifications',
      initialState,
      reducers: {
        clearNotifications: state => {
          state.error = null
          state.success = null
        },
        setError: (state, action) => {
          state.success = null
          state.error = action.payload
        },
        setSuccess: (state, action) => {
          state.success = action.payload
          state.error = null
        },
      },
      extraReducers: builder => {
        builder
          .addMatcher(
            isAnyOf(
              getUser.fulfilled,
            ),
            (state, action) => {
              state.error = null
              state.success = action.payload.message
            }
          )
          .addMatcher(
            isAnyOf(
              getUser.rejected
              // can add as many imported actions
              // as you like to these
            ),
            (state, action) => {
              state.error = action?.payload
              state.success = null
            }
          )
          // reset all messages on pending
          .addMatcher(
            isAnyOf(
              getUser.pending
            ),
            (state, action) => {
              state.error = null
              state.success = null
            }
          )
      },
    })
    export const { clearNotifications, setError, setSuccess } = notificationsSlice.actions
    
    export default notificationsSlice.reducer
    
    export const getErrorMsg = state => state.notifications.error
    export const getSuccessMsg = state => state.notifications.success
    
    

    添加上述内容后,您现在可以创建一个用于监听的通知组件

      const error = useSelector(getErrorMsg)
      const success = useSelector(getSuccessMsg)
    

    并相应地显示消息。

    警告:

    • 我的 notificationSlice 代码假定当一个动作完成时,成功负载上将存在一个“消息”对象。因此,在我的异步 thunk 上,如果我的 api 没有返回 this,我必须将它显式添加到结果中。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2017-07-03
      • 2019-04-20
      • 1970-01-01
      • 2019-06-11
      • 2019-07-06
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多