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

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
前端小万5 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁5 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
李少兄5 天前
JavaScript 隐式全局变量解析
javascript