Redux基本结构

Redux基本结构.md

在项目中使用 Redux 进行状态管理时,通常的基本思路和文件结构如下:

基本思路

  1. 安装 Redux 和相关库:
    • 安装 reduxreact-redux 以及 Redux 开发工具扩展。
      npm install redux react-redux @reduxjs/toolkit
      
  2. 定义 Slice(切片):
    • 使用 createSlice 定义你的 slice,包括状态、reducers 和 actions。
  3. 创建 Redux Store:
    • 使用 configureStore 创建 Redux store,并将所有 slice 的 reducer 组合在一起。
  4. 提供 Store:
    • 使用 Provider 组件将 Redux store 提供给你的 React 应用。
  5. 使用状态和分发 Actions:
    • 使用 useSelector 从 Redux store 中获取状态,使用 useDispatch 分发 actions。

文件结构

以下是一个常见的 Redux 文件结构示例:

src/
│
├── app/
│   ├── store.js          // 配置 Redux store
│
├── features/
│   ├── counter/
│   │   ├── counterSlice.js  // 定义 counter 的 slice
│   │   ├── Counter.js       // Counter 组件
│   │
│   ├── user/
│       ├── userSlice.js     // 定义 user 的 slice
│       ├── User.js          // User 组件
│
├── App.js                  // 顶层应用组件
└── index.js                // 应用入口

具体实现步骤

  1. 配置 Redux Store(src/app/store.js):
    import { configureStore } from '@reduxjs/toolkit';
    import counterReducer from '../features/counter/counterSlice';
    import userReducer from '../features/user/userSlice';
    
    export const store = configureStore({
      reducer: {
        counter: counterReducer,
        user: userReducer,
      },
    });
    
  2. 定义 Slice(src/features/counter/counterSlice.js):
    import { createSlice } from '@reduxjs/toolkit';
    
    export const counterSlice = createSlice({
      name: 'counter',
      initialState: {
        value: 0,
      },
      reducers: {
        increment: state => {
          state.value += 1;
        },
        decrement: state => {
          state.value -= 1;
        },
        incrementByAmount: (state, action) => {
          state.value += action.payload;
        },
      },
    });
    
    export const { increment, decrement, incrementByAmount } = counterSlice.actions;
    
    export default counterSlice.reducer;
    
  3. 顶层应用组件(src/App.js):
    import React from 'react';
    import Counter from './features/counter/Counter';
    import User from './features/user/User';
    
    function App() {
      return (
        <div className="App">
          <Counter />
          <User />
        </div>
      );
    }
    
    export default App;
    
  4. 提供 Store(src/index.js):
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from 'react-redux';
    import { store } from './app/store';
    import App from './App';
    
    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );
    
  5. 使用状态和分发 Actions(src/features/counter/Counter.js):
    import React from 'react';
    import { useSelector, useDispatch } from 'react-redux';
    import { increment, decrement, incrementByAmount } from './counterSlice';
    
    function Counter() {
      const count = useSelector(state => state.counter.value);
      const dispatch = useDispatch();
    
      return (
        <div>
          <div>
            <button onClick={() => dispatch(decrement())}>
              - 
            </button>
            <span>{count}</span>
            <button onClick={() => dispatch(increment())}>
              + 
            </button>
          </div>
          <button onClick={() => dispatch(incrementByAmount(5))}>
            Add 5
          </button>
        </div>
      );
    }
    
    export default Counter;
    

总结

通过上述步骤,你可以在项目中成功集成 Redux 并使用它来管理应用状态。根据项目的复杂程度,你可以进一步细化和扩展文件结构,例如将 API 调用逻辑抽象到异步 action 中,或使用中间件(如 Redux Thunk)来处理复杂的异步逻辑。

Written on July 1, 2024