You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何导出使用prepare函数的Redux Toolkit reducer?

问题分析与解决方法

你的代码结构不符合Redux Toolkit的createSlice规范,导致无法正确导出目标action creator。

错误原因

在createSlice的reducers配置中,每个键名应该是action的名称,对应的对象需要包含reducer(状态更新逻辑)和prepare(处理参数)函数。你现在把createNotification嵌套在了test对象里,Redux Toolkit只会识别test作为action名称,生成名为test的action creator,自然找不到createNotification。

修正方案

直接将createNotification作为reducers的顶层键,对应的对象包含reducer和prepare函数:

import { createSlice } from "@reduxjs/toolkit";

const notificationSlice = createSlice({
  name: 'notification',
  initialState: '',
  reducers: {
    createNotification: {
      // 状态更新逻辑
      reducer(state, action) {
        console.log(action);
        // 示例:将通知内容设为payload的第一个参数
        return action.payload[0];
      },
      // 参数预处理函数
      prepare(...args) {
        return {
          payload: args
        }
      }
    }
  }
})

// 正常导出action creator
export const { createNotification } = notificationSlice.actions
export default notificationSlice.reducer

特殊情况处理(不推荐)

如果一定要保留test这个结构,你可以通过重命名导出的方式,将生成的test action creator改名为createNotification:

// 重命名导出
export const { test: createNotification } = notificationSlice.actions

但这种方式会让action的类型变为notification/test,不符合语义化命名规范,因此更推荐第一种修正方案。


内容的提问来源于stack exchange,提问作者SupraCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:43:27