安装
npm install @reduxjs/toolkit react-redux
- Redux Toolkit 是官方推荐编写Redux的逻辑方式,用于简化书写方式
- React-redux 用来链接Redux和React组件之间的中间件
使用
定义数据
创建要管理的数据模块 store/module/counter.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'const counterSlice = createSlice({name: 'counter',initialState: {counter: 0, // 初始值},reducers: {// 修改值的方法changeCounter: (state, { payload }: PayloadAction<number>) => {state.counter = payload // 使传入的参数赋值到counter},}
})export const { changeCounter } = counterSlice.actions // 导出修改的方法
export default counterSlice.reducer
创建store/index.ts用于管理和导出项目所含的状态数据
import { configureStore } from '@reduxjs/toolkit'
import { useSelector, useDispatch } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'
import counterReducer from './module/counter' // 管理的模块const store = configureStore({reducer:{counter: counterReducer // 定义管理的模块}
})type RootState = ReturnType<typeof store.getState>
type AppDispatch = typeof store.dispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector // 导出使用数据的方法
export const useAppDispatch: () => AppDispatch = useDispatch // 导出修改数据的方法
export default store
为React注入store
在项目主入口main.tsx中, 使用Provider标签包裹来注入store
import { Provider } from "react-redux";
import store from "@/store/index.ts";createRoot(document.getElementById("root") as HTMLElement).render(<Provider store={store}><App /></Provider>
);
页面中使用/修改数据
import { useAppSelector, useAppDispatch } from "@/store";
import { changeCounter } from "@/store/module/counter";const { count, text } = useAppSelector((state) => ({count: state.counter.counter, // 取值
}));// 修改方法
const dispatch = useAppDispatch();
function handlecChangeCount() {dispatch(changeCounter(count + 1));
}return (<><div>{count}</div><button onClick={handlecChangeCount}>change</button></>);