面试被问到-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...

相关推荐
yuanyxh2 小时前
Mac 软件推荐
前端·javascript·程序员
万少2 小时前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木2 小时前
Web自动化测试
前端·python·pycharm·pytest
Kagol3 小时前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel4 小时前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者4 小时前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白4 小时前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg5 小时前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫5 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫5 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome