redux 结合 @reduxjs/toolkit 的使用

1,使用步骤

使用React Toolkit 创建 counterStore(store目录下) --> 为React注入store(src下面的index) --> React组件使用store中的数据(组件)

2,例如下面有一个简单加减的案例

先来看一下项目目录

counterStore代码:

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

const counterStore = createSlice({
  // 模块名称独一无二
  name: 'counter',
  // 初始数据
  initialState: {
    count: 1
  },
  // 修改数据的同步方法
  reducers: {
    increment (state) {
      state.count++
    },
    decrement(state){
      state.count--
    }
  }
})
// 结构出actionCreater
const { increment,decrement } = counter.actions

// 获取reducer函数
const counterReducer = counterStore.reducer

// 导出
export { increment, decrement }
export default counterReducer

store下面 index 的代码:

复制代码
import { configureStore } from '@reduxjs/toolkit'

import counterReducer from './modules/counterStore'

export default configureStore({
  reducer: {
    // 注册子模块
    counter: counterReducer
  }
})

src下面index 的代码:

复制代码
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
// 导入store
import store from './store'
// 导入store提供组件Provider
import { Provider } from 'react-redux'

ReactDOM.createRoot(document.getElementById('root')).render(
  // 提供store数据
  <Provider store={store}>
    <App />
  </Provider>
)

App的代码:

复制代码
import { useSelector, useDispatch } from 'react-redux'
import {decrement,increment} from './store/modules/counterStore'

function App(){
  const dispatch = useDispatch()
  // 错误使用
  // const count = useSelector(state=>state.counter)
  // 正确使用
  const {count} = useSelector(state=>state.counter)
  return (
    <div>
      <button onClick={()=>dispatch(decrement())}>-</button>
      <h1>
        {count}
      </h1>
      <button onClick={()=>dispatch(increment())}>+</button>
    </div>
  );
}

export default App;

页面是这样的,点击加减数字就会改变了

相关推荐
天黑请闭眼13 小时前
视频文件上传至服务器后浏览器无法在线播放
前端
一位搞嵌入式的 genius13 小时前
前端实战开发(四):从迭代器到异步编程:ES6 Generator 全面解析 + 实战问题排查
开发语言·前端·es6·前端实战
来来走走13 小时前
Android开发(Kotlin) 高阶函数、内联函数
android·开发语言·kotlin
拉不动的猪13 小时前
# 关于初学者对于JS异步编程十大误区
前端·javascript·面试
玖釉-13 小时前
解决PowerShell执行策略导致的npm脚本无法运行问题
前端·npm·node.js
Murphy_lx13 小时前
C++ thread类
开发语言·c++
彩妙不是菜喵13 小时前
C++ 中 nullptr 的使用与实践:从陷阱到最佳实践
开发语言·jvm·c++
lskisme13 小时前
springboot maven导入本地jar包
开发语言·python·pycharm
Larcher13 小时前
新手也能学会,100行代码玩AI LOGO
前端·llm·html
徐子颐14 小时前
从 Vibe Coding 到 Agent Coding:Cursor 2.0 开启下一代 AI 开发范式
前端