redux 数据流通的过程?

Redux 数据流通的完整过程(单向数据流)

Redux 的核心思想就是:状态只存在一个地方,所有变化都是可预测的、可追踪的,并且遵循单向数据流。

下面是完整流程,从 UI 到 Action → Reducer → Store → UI:

1. UI 触发 Action

UI(React 组件)中用户操作,触发一个 action:

dispatch({
  type: 'ADD_TODO',
  payload: '学习 Redux'
})

也可能是通过 action creator:

dispatch(addTodo('学习 Redux'));

Action 只是一个普通对象,描述“发生了什么”。

2. dispatch(action) 发送给 Store

dispatch() 是唯一触发状态更新的方式。

Redux 接到 action 后,会把它交给 reducer 处理。

3. Reducer 根据 Action 更新 State(纯函数)

Reducer 是一个纯函数:

(state, action) => newState

示例:

function todoReducer(state = initialState, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        list: [...state.list, action.payload]
      };
    default:
      return state;
  }
}

Reducer 不能修改原 state,只能返回新 state。

4. Store 保存新 State

Redux Store 接收到 reducer 产出的 newState

覆盖原 state
保存最新的全局状态

5. UI(React)重新渲染

React-Redux(connect / useSelector)会订阅 store:

当 store 改变时:

  • 自动触发组件重新渲染
  • UI 更新为最新数据

举例:

const todos = useSelector(state => state.todos);

当 state 更新时,该组件会自动刷新。

Redux 数据流闭环:

   UI 触发事件
        ↓
   dispatch(action)
        ↓
   Reducer 计算新 state
        ↓
   Store 更新状态
        ↓
React UI 自动刷新

全程 单向数据流(One-way data flow)
状态变化可追溯
数据管理可控、稳定

简单举例(完整流程)

// 1. Action Creators
const add = () => ({ type: 'ADD' });

// 2. Reducer
function counter(state = 0, action) {
  switch (action.type) {
    case 'ADD':
      return state + 1;
    default:
      return state;
  }
}

// 3. Component
function App() {
  const count = useSelector(state => state.counter);
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch(add())}>
      点击 +1 ({count})
    </button>
  );
}

按下按钮:

  • dispatch(send action)
  • reducer(state + 1)
  • store 更新
  • UI 自动刷新

总结

Redux 数据流就是 5 步:

  1. 用户操作 → dispatch(action)

  2. Store 接收 action

  3. Reducer 返回新 state

  4. Store 保存 state

  5. React UI 自动刷新

关键词:单向数据流、可预测性、纯函数 reducer、集中式 store

posted @ 2025-11-26 09:30  煜火  阅读(7)  评论(0)    收藏  举报