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

相关推荐
用户059540174463 分钟前
把前端内存泄漏排查从2小时压到5分钟,我们把它集成进了CI
前端·css
申君健24864182772021 小时前
Vapor 核心数据结构:Block原理
前端
Csvn1 小时前
工程化专题 | 改完组件保存,浏览器毫无反应,重启 dev server 又好了——气不气?
前端
我有满天星辰1 小时前
Vue 指令完全指南:从 Vue 2 到 Vue 3 的演进与实战
前端·javascript·vue.js
光影少年1 小时前
RN 渲染原理:不依赖WebView,原生控件渲染
前端·react native·react.js·前端框架
小白学过的代码1 小时前
# flv.js / mpegts.js 播不了国标摄像头(H.265 + G.711A)?纯前端 Jessibuca 无后端方案(附完整代码)
前端·javascript·h.265
console.log('npc')1 小时前
AI Agent 前端流式渲染核心技术文档(SSE \+ WebSocket \+ 打字机渲染)
前端·人工智能·websocket
法外狂徒12 小时前
将 Pi Agent 接入 HagiCode 的实践之路
服务器·前端·人工智能
IT_陈寒2 小时前
React中useEffect的依赖项把我坑惨了
前端·人工智能·后端
广州华水科技2 小时前
单北斗GNSS在变形监测中的优势与应用分析
前端