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

相关推荐
代码游侠8 小时前
C语言核心概念复习——C语言基础阶段
linux·开发语言·c++·学习
㓗冽9 小时前
60题之内难题分析
开发语言·c++·算法
dingdingfish9 小时前
Bash学习 - 第3章:Basic Shell Features,第5节:Shell Expansions
开发语言·学习·bash
rainbow68899 小时前
C++开源库dxflib解析DXF文件实战
开发语言·c++·开源
deepxuan9 小时前
Day7--python
开发语言·python
晚霞的不甘9 小时前
Flutter for OpenHarmony天气卡片应用:用枚举与动画打造沉浸式多城市天气浏览体验
前端·flutter·云原生·前端框架
禹凕9 小时前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
xkxnq9 小时前
第五阶段:Vue3核心深度深挖(第74天)(Vue3计算属性进阶)
前端·javascript·vue.js
三小河9 小时前
Agent Skill与Rules的区别——以Cursor为例
前端·javascript·后端
蜡笔小马9 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree