react redux和@reduxjs/toolkit工具

1,安装

复制代码
npm i @reduxjs/toolkit react-redux

2,目录

  • store
    • modules
      • counterStore.js
    • index.js

3,最外层index.js引入

javascript 复制代码
import store from './store'
import { Provider } from 'react-redux'
  <Provider store={store}>
    <App />
  </Provider>

4,编写counterStore.js

javascript 复制代码
import { createSlice } from "@reduxjs/toolkit"

const counterStore = createSlice({
  name: 'counter',
  // 初始化state
  initialState: {
    count: 0
  },
  // 修改状态的方法 同步方法 支持直接修改
  reducers: {
    inscrement (state) {
      state.count++
    },
    decrement (state) {
      state.count--
    }
  }
})

// 解构出来actionCreate函数
const { inscrement, decrement } = counterStore.actions

// 获取reducer
const reducer = counterStore.reducer

// 以按需的方式导出actionCreate
export { inscrement, decrement }

// 以默认导出方式导出reducer
export default reducer

5,store/index.js引入子模块

javascript 复制代码
import { configureStore } from "@reduxjs/toolkit"
// 导入子模块reducer
import counterReducer from "./modules/counterStore"

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
})

export default store

6,相应文件调用

javascript 复制代码
import { useSelector, useDispatch } from "react-redux"
// 导入创建action对象的方法
import { inscrement, decrement } from "./store/modules/counterStore"

function App () {
  // 这里的state.counter的counter与store/index.js下的counter相对应
  const { count } = useSelector(state => state.counter)
  // 得到dispatch函数
  const dispatch = useDispatch()
  return (
    <div className="App">
      {/* 调用dispatch提交action对象 */}
      <button onClick={() => dispatch(inscrement())}>++</button>
      {count}
      <button onClick={() => dispatch(decrement())}>--</button>
    </div>
  )
}

export default App

7,提交action传参实现需求

在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上

javascript 复制代码
// counterStore.js
  reducers: {
    // 传参
    addToNumber (state, action) {
      state.count = action.payload
    }
  }
  // 添加addToNumber
const { addToNumber } = counterStore.actions
export { addToNumber }

使用

javascript 复制代码
import { addToNumber } from "./store/modules/counterStore"
<button onClick={() => dispatch(addToNumber(10))}>to 10</button>
相关推荐
前端精髓3 小时前
移除 Effect 依赖
前端·javascript·react.js
菲利普马洛6 小时前
记一次主题闪烁问题
前端·css·react.js
宇擎智脑科技9 小时前
Claude Code 源码分析(七):终端 UI 工程 —— 用 React Ink 构建工业级命令行界面
前端·人工智能·react.js·ui·claude code
Ruihong13 小时前
🚀 Vue 一键转 React!企业后台 VuReact 混写迁移实战
vue.js·react.js
@大迁世界14 小时前
17.在 React 中如何根据条件决定渲染哪个组件?
前端·javascript·react.js·前端框架·ecmascript
lihaozecq1 天前
我用 1 天的时间 vibe coding 了一个多人德州扑克游戏
前端·react.js·ai编程
Highcharts.js1 天前
高级可视化图表的暗色模式与主题|Highcharts 自适应主题配色全解
前端·react.js·实时图表
ISkp3V8b41 天前
从 ReAct 到 Workflow:基于云端 API 构建事件驱动的智能体
前端·react.js·前端框架
谢尔登1 天前
【React】setState 触发渲染的流程
前端·react.js·前端框架
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:lottie-react-native — Lottie动画组件
react native·react.js·harmonyos