面试被问到-redux-toolkit用法

安装使用
npm install @reduxjs/toolkit react-redux

  1. 创建store
js 复制代码
// store.js
import { configureStore } from "@reduxjs/toolkit";
// import { configureStore } from "../rtk-nut";
import countReducer from "./counterSlice";

export default configureStore({
  reducer: {
    counter: countReducer,
  },
});
  1. 创建 Slice
js 复制代码
import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0,
  },
  reducers: {
    increment: (state) => {
      state.count++;
    },
    decrement: (state) => {
      state.count -= 1;
    },
    incrementByAmount: (state, action) => {
      console.log(action, "action"); // {type: 'counter/incrementByAmount', payload: 2}

      state.count += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
  1. 组件中使用
js 复制代码
import { useReducer, useEffect } from "react";
import store from "../store/rtkStore";
import { increment, decrement, incrementByAmount } from "../store/counterSlice";

export default function ReduxToolkitPage() {
 const count = store.getState().counter.count;
 const [, forceUpdate] = useReducer((x) => x + 1, 0);

 useEffect(() => {
   const unlistener = store.subscribe(() => {
     forceUpdate();
   });
   return () => {
     unlistener();
   };
 }, []);
 return (
   <div>
     <h2>ReduxToolkitPage</h2>
     <div>{count}</div>
     <button
       onClick={() => {
         store.dispatch(increment());
       }}
     >
       increment
     </button>
     <button
       onClick={() => {
         store.dispatch(decrement());
       }}
     >
       decrement
     </button>
     <button
       onClick={() => {
         store.dispatch(incrementByAmount(2));
       }}
     >
       incrementByAmount
     </button>
   </div>
 );
}

redux-toolkit原理实现 todo...

相关推荐
狗哥哥19 分钟前
微前端路由设计方案 & 子应用管理保活
前端·架构
前端大卫1 小时前
Vue3 + Element-Plus 自定义虚拟表格滚动实现方案【附源码】
前端
却尘1 小时前
Next.js 请求最佳实践 - vercel 2026一月发布指南
前端·react.js·next.js
ccnocare1 小时前
浅浅看一下设计模式
前端
Lee川1 小时前
🎬 从标签到屏幕:揭秘现代网页构建与适配之道
前端·面试
Ticnix2 小时前
ECharts初始化、销毁、resize 适配组件封装(含完整封装代码)
前端·echarts
纯爱掌门人2 小时前
终焉轮回里,藏着 AI 与人类的答案
前端·人工智能·aigc
twl2 小时前
OpenClaw 深度技术解析
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Grok API 申请及使用
前端
星光不问赶路人2 小时前
vue3使用jsx语法详解
前端·vue.js