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>
相关推荐
张元清12 小时前
React useDisclosure Hook:管理模态框和抽屉的打开关闭状态 (2026)
javascript·react.js
学高数就犯困12 小时前
React:常见的性能优化手段
前端·react.js
濮水大叔13 小时前
为什么 AI 最擅长 React/Next.js,却很少看到真正好用的 Next.js 开源项目?
react.js·node.js·next.js
Cloud_bread15 小时前
从ReAct到自主闭环:Agentic Coding核心执行引擎的技术演进
前端·react.js·前端框架
Darling噜啦啦18 小时前
React 组件进化论:从状态混乱到 UI = fn(props) 的三次重构
react.js
无人生还18 小时前
从 Vue3 到 React · 快速上手系列第 10 篇:路由
前端·vue.js·react.js
deepThinking18 小时前
从项目里回看 React 生态:React 18/19 新特性、我们踩过的坑,以及那些"用旧写法写出的新思想
react.js
FogLetter18 小时前
我真的写了个“诈尸式”缓存组件:手撕React KeepAlive
前端·react.js·面试
LaughingZhu20 小时前
Product Hunt 每日热榜 | 2026-08-02
前端·神经网络·react.js·搜索引擎·前端框架
无人生还2 天前
从 Vue3 到 React · 快速上手系列第 9 篇:自定义 Hook(对标 Composables)
前端·vue.js·react.js