1. 安装
npm install @reduxjs/toolkit react-redux
2.创建store目录
3. 创建counterStore.js
// 使用RTK创建store, createSlice 创建reducer的切片 import {createSlice } from "@reduxjs/toolkit"; const counterSlice = createSlice({ // 需要一个配置对象作为参数,通过对象的不同属性来指定它的配置 name:'counter', // 用来自动生成 action 中的 type initialState:{ // state的初始值 count:0 }, // 指定state的各种操作,直接在对象中添加方法 reducers:{ inscrement: state => { // state是一个代理对象,可直接修改 state.count ++ }, decrement: state => { state.count -- } } }) // 切片对象会自动的帮助我们生成action export const { inscrement,decrement } = counterSlice.actions // 导出 reducer export default counterSlice.reducer
3. store/index.js
import { configureStore } from "@reduxjs/toolkit"; import counterReducer from './modules/counterStore' // 创建store对象 const store = configureStore({ reducer:{ counter:counterReducer } }) export default store
4. 在src/index.js文件中如下
import { Provider } from 'react-redux'; import store from './store'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode> );
5. 在组件中使用
import { useSelector,useDispatch } from "react-redux" import{inscrement,decrement} from './store/modules/counterStore' // useSelector() 用来加载state中的数据 const {count} = useSelector(state => state.counter) // 通过useDispatch() 来获取派发器对象 const dispatch = useDispatch() <div> store count: {count} <button onClick={()=>dispatch(inscrement())}> ++</button> <button onClick={()=>dispatch(decrement())}>--</button> </div>
标签:基本,count,const,react,state,import,redux,store From: https://www.cnblogs.com/jlyuan/p/18121858