裸用 Redux

“裸用 Redux” 指只安装并使用 redux 包,不引入 React 绑定层或官方工具包。这种方式可以帮助理解 Redux 的底层模型,但在真实 React 项目中通常会继续使用 react-redux@reduxjs/toolkit

安装

pnpm add redux

定义 Store

src/store/index.js
import { createStore } from 'redux';

const initialState = {
  msg: '张三',
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'SET_MSG':
      return { ...state, msg: action.payload };
    default:
      return state;
  }
}

const store = createStore(reducer);

export default store;

使用状态

直接通过 store.getState() 读取状态。

src/App.jsx
import store from './store';

export default function App() {
  const { msg } = store.getState();

  return <div>{msg}</div>;
}

更新状态

通过 store.dispatch() 派发 action。

src/components/Tips.jsx
import store from '../store';

export default function Tips() {
  return (
    <button
      type="button"
      onClick={() => {
        store.dispatch({
          type: 'SET_MSG',
          payload: '李四',
        });
      }}
    >
      更新消息
    </button>
  );
}

监听变化

裸用 Redux 时,如果 UI 需要跟随 store 变化重新渲染,需要手动订阅。

src/App.jsx
import { useEffect, useState } from 'react';
import store from './store';

export default function App() {
  const [msg, setMsg] = useState(store.getState().msg);

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setMsg(store.getState().msg);
    });

    return unsubscribe;
  }, []);

  return <div>{msg}</div>;
}

Action Creator

在大型项目中,不建议把 action 对象散落在组件里。可以用 action creator 统一生成 action。

src/store/action-creator.js
export const setMsg = (payload) => ({
  type: 'SET_MSG',
  payload,
});

组件中只关心业务动作:

src/components/Tips.jsx
import store from '../store';
import { setMsg } from '../store/action-creator';

export default function Tips() {
  return (
    <button
      type="button"
      onClick={() => {
        store.dispatch(setMsg('李四'));
      }}
    >
      更新消息
    </button>
  );
}

适用场景

裸用 Redux 适合学习底层机制,或在非 React 环境中管理状态。React 项目中建议使用 react-redux 处理订阅和渲染更新,再配合 Redux Toolkit 减少模板代码。