Redux和@reduxjs/toolkit同时在Next.js项目中使用

安装

yarn add @reduxjs/toolkit react-redux

Store文件夹

index.ts:

javascript 复制代码
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
import commonSlice from './commonSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
    common: commonSlice
  },
});

commonSlice.ts:

javascript 复制代码
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

const initialState = {
  isLoading: false,
};

const counterSlice = createSlice({
  name: 'common',
  initialState,
  reducers: {
    setState: (state: any, action: PayloadAction<any>) => {
      switch (action.payload.type) {
        case 'SET_COMMON_STATE':
          state[action.payload.key] = action.payload.value
          break
        default:
          state
      }
    },
  },
});

// 导出 action 方法(供组件调用)
export const { setState } = counterSlice.actions;

// 导出切片的 reducer(供 store 配置)
export default counterSlice.reducer;

counterSlice.ts:

javascript 复制代码
// store/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
 
// 初始状态
const initialState = {
  value: 0,
};
 
// 创建切片(包含状态和修改状态的方法)
const counterSlice = createSlice({
  name: 'counter', // 切片名称(用于区分不同状态)
  initialState,
  reducers: {
    // 定义增加计数的方法
    increment: (state) => {
      state.value += 1; // Redux Toolkit 内部自动处理了不可变性
    },
    // 定义减少计数的方法
    decrement: (state) => {
      state.value -= 1;
    },
  },
});
 
// 导出 action 方法(供组件调用)
export const { increment, decrement } = counterSlice.actions;
 
// 导出切片的 reducer(供 store 配置)
export default counterSlice.reducer;

入口文件

javascript 复制代码
"use client"

import type React from "react"
import { Analytics } from "@vercel/analytics/next"
import { Suspense } from "react"
import { Loading } from '@/components/index'
import { Provider } from 'react-redux';
import { store } from '@/store';
import "./globals.css"

export default function Index({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <Provider store={store}>
      <Suspense fallback={null}>
        {children}
        <Analytics />
        <Loading></Loading>
      </Suspense>
    </Provider>
  )
}

测试文件

javascript 复制代码
"use client"
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '@/store/counterSlice';
import { setState } from '@/store/commonSlice'
import { Button } from 'antd'


export default function Home() {
  const count = useSelector((state: any) => state.counter.value);
  const common = useSelector((state: any) => state.common);

  const dispatch = useDispatch();

  const handleTest1 = () => {
    dispatch(setState({ type: 'SET_COMMON_STATE', key: 'isLoading', value: true }))
  }
  const handleTest2 = () => {
    dispatch(setState({ type: 'SET_COMMON_STATE', key: 'isLoading', value: false }))
  }
  return (
    <div style={{ padding: 20 }}>
      <p>当前计数:{count}</p>
      <Button type='primary' className='m-space' onClick={() => dispatch(increment())}>+</Button>
      <Button type='primary' onClick={() => dispatch(decrement())}>-</Button>
      <div>{common.isLoading + ''}</div>
      <Button type='primary' className='m-space' onClick={() => handleTest1()}>true</Button>
      <Button type='primary' onClick={() => handleTest2()}>false</Button>
    </div>
  );
}
  • @reduxjs/toolkit(RTK)基于 immer 库,允许你在 createSlice 等 reducer 里直接写"可变代码"(比如 state.value = 1),实际底层 immer 会保证你的 state 仍是不可变数据(immutable)。
  • Redux Toolkit 自动帮你处理了不可变性问题,无需再手动深拷贝或其它 immutable 库辅助。

参考链接:

https://blog.csdn.net/2408_89348881/article/details/150471740

相关推荐
九酒9 分钟前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
Jackson__1 小时前
做了一段时间的AI coding后,我终于搞清了 CLI 和 MCP 的区别
前端·agent·ai编程
IT_陈寒3 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569154 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔5 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6876 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen7 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding9 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693559 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill9 小时前
curl命令学习笔记一
前端