总结
- 运用 createSlice 创建 counterSlice,包括 initialState、reducers,其中 reducers 是必须
- 通过 configureStore 保存 store
- 自定义了 useAppSelector、useAppDispatch、shallowEqualApp
- 组件整体用 Provider 包裹
- 从 useAppSelector 中获取 store 中的属性值
- 从 useAppDispatch 修改 store 中的属性值
安装
npm install @reduxjs/toolkit react-redux
代码
-
配置
src\store\modules\counter.tsimport { createSlice } from '@reduxjs/toolkit' const counterSlice = createSlice({ name: 'counter', initialState: { count: 100, message: 'Hello Redux' }, reducers: { changeMessageAction(state, { payload }) { state.message = payload } } }) export const { changeMessageAction } = counterSlice.actions export default counterSlice.reducersrc\store\index.tsimport { configureStore } from '@reduxjs/toolkit' import { useSelector, useDispatch, TypedUseSelectorHook, shallowEqual } from 'react-redux' import counterReducer from './modules/counter' const store = configureStore({ reducer: { counter: counterReducer } }) type GetStateFnType = typeof store.getState type IRootState = ReturnType<GetStateFnType> type DispatchType = typeof store.dispatch // useAppSelector的hook export const useAppSelector: TypedUseSelectorHook<IRootState> = useSelector export const useAppDispatch: () => DispatchType = useDispatch export const shallowEqualApp = shallowEqual export default store -
应用
src\views\redux-demo\index.tsximport React, { memo } from 'react' import type { FC, ReactNode } from 'react' import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store' import { changeMessageAction } from '@/store/modules/counter' interface IProps { children?: ReactNode } const ReduxDemo: FC<IProps> = () => { const { count, message } = useAppSelector( (state) => ({ count: state.counter.count, message: state.counter.message }), shallowEqualApp ) /** 事件处理函数 */ const dispatch = useAppDispatch() function handleChangeMessage() { dispatch(changeMessageAction('呵呵呵呵呵')) } return ( <> ReduxDemo <h2>当前计数: {count}</h2> <h2>当前消息: {message}</h2> <button onClick={handleChangeMessage}>修改message</button> </> ) } export default memo(ReduxDemo)src\index.tsximport React from 'react' import ReactDOM from 'react-dom/client' import { HashRouter } from 'react-router-dom' import { Provider } from 'react-redux' import 'normalize.css' import './assets/css/index.less' import store from './store' import App from '@/App' const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement) root.render( <Provider store={store}> <HashRouter> <App /> </HashRouter> </Provider> )