前言

redux状态管理插件的使用


提示:以下是本篇文章正文内容,下面案例可供参考

redux状态管理

安装redux

npm install @reduxjs/toolkit react-redux

创建文件 并使用

import { configureStore } from "@reduxjs/toolkit";

//子模块导入,可自定义多个
import counterStore from "./modules/counterStore";

// 创建store组合子模块
const store = configureStore({
  reducer:{
    counterStore,
  }
})

export default store
import { createSlice } from "@reduxjs/toolkit";

const counterStore = createSlice({
  name: "todos",
  // 存储数据
  initialState: {
    count:0
  },
  // 方法逻辑函数
  reducers: {
    inscrement(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    },
  },
});

// 导出
export const { decrement, inscrement } = counterStore.actions;
export default counterStore.reducer;
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from "./store";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
       <Provider store={store}>
          <App />
       </Provider>
  </React.StrictMode>
);
reportWebVitals();
import { useSelector,useDispatch } from "react-redux";
import { inscrement,decrement } from "./store/modules/counterStore";

import './App.css';

import Home from "./components/home";
function App() {
  // react-redux中间件导入 useSelector() 函数获取store参数
  const {count} = useSelector(state=>state.counterStore)
  // react-redux中间件导入 useSelector() 函数获取store函数使用
  const dispach = useDispatch()
  return (
    <div 
    className="App active"
    > 
      {count}
      <button type="" onClick={()=>dispach(inscrement())}>++</button>
      <button type="" onClick={()=>dispach(decrement())}>--</button>
      <Home>
        <span>12222</span>
      </Home>
    </div>
  );
}

export default App;

传参action


总结

redux状态管理插件的使用

03-06 09:48