redux

redux 三大原则

  1. 单一数据源
  2. 状态是只读的
  3. 状态修改均由纯函数完成

使用

通常不直接使用,而是通过 @reduxjs/toolkit 来简化使用

  • 创建 slice 对象

    // store/counterSlice.ts
    import { createSlice } from '@/reduxjs/toolkit';
    
    export const counterSlice = createSlice({
        name: 'counter',
        initialState: {
            value: 0,
        },
        reducers: {
            fn1: (state) => {
                state.value += 1;
            },
        },
    });
    
    export const { fn1 } = counterSlice.actions;
    export default counterSlice.reducer;
    
  • 创建 store 对象

    // store/index.ts
    import { configureStore } from '@reduxjs/toolkit';
    import counterReducer from './conterSlice';
    
    const store = configureStore({
        reducer: {
            counter: counterReducer,
        },
    });
    
    export default store;
    
    // 定义类型
    // 从 store 本身推断 `RootState` 和 `AppDispatch` 类型
    export type RootState = ReturnType<typeof store.getState>;
    // 推断类型:{counter: CounterState}
    export type AppDispatch = typeof store.dispatch;
    
  • 创建全局 hooks,方便调用 store

    // hooks.ts
    // 定义全局类型化 hooks,避免每次都手动输入 RootState
    import {
        TypedUseSelectorHook,
        useDispatch,
        useSelector,
    } from 'react-redux';
    import type { RootState, AppDispatch } from './store';
    
    export const useAppDispatch: () => AppDispatch = useDispatch;
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
    
  • 使用

    import { useAppSelector, useAppDispatch } from '@/hooks';
    import { fn1 } from '@/store/counterSlice';
    
    const count = useAppSelector((state) => state.counter.value);
    const dispatch = useAppDispatch();
    
    dispatch(fn1());
    
Last Updated:
Contributors: af, zhangfei