返回

剖析 Redux 原理:从零开始实现 Redux

前端

想要真正理解 Redux 的运作原理,最好的方法莫过于亲手打造一个属于自己的 Redux。在这个过程中,我们将深入探索 Redux 的核心概念,掌握它的 API 用法,并最终揭开 Redux 神秘的面纱。

为了便于理解,我们将从头开始构建一个简化版的 Redux,它包含以下几个关键组件:

  • Store: 应用程序状态的唯一来源,负责存储和管理应用程序数据。
  • Action: 应用程序状态变更的纯函数。
  • Reducer: 响应 Action,并更新 Store 中的状态。

1. 创建 Store

首先,我们需要创建一个 Store 来管理应用程序的状态。Store 可以被看作是一个容器,它包含了应用程序的所有数据,并提供了一系列方法来访问和更新这些数据。

class Store {
  constructor(reducer, initialState) {
    this.reducer = reducer;
    this.state = initialState;
  }

  getState() {
    return this.state;
  }

  dispatch(action) {
    this.state = this.reducer(this.state, action);
  }
}

2. 定义 Action

接下来,我们需要定义一些 Action,这些 Action 将用于应用程序状态的变更。Action 通常是一个简单的对象,包含一个 type 属性,用于标识 Action 的类型,以及一些其他属性,用于携带需要更新的数据。

const ADD_TODO = 'ADD_TODO';
const REMOVE_TODO = 'REMOVE_TODO';
const UPDATE_TODO = 'UPDATE_TODO';

const addTodo = (text) => ({
  type: ADD_TODO,
  text,
});

const removeTodo = (id) => ({
  type: REMOVE_TODO,
  id,
});

const updateTodo = (id, text) => ({
  type: UPDATE_TODO,
  id,
  text,
});

3. 实现 Reducer

Reducer 是 Redux 的核心之一,它负责响应 Action,并更新 Store 中的状态。Reducer 是一个纯函数,这意味着它不会产生副作用,并且总是返回一个新的状态对象。

const todoReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [...state, { id: Date.now(), text: action.text, completed: false }];
    case REMOVE_TODO:
      return state.filter((todo) => todo.id !== action.id);
    case UPDATE_TODO:
      return state.map((todo) => todo.id === action.id ? { ...todo, text: action.text } : todo);
    default:
      return state;
  }
};

4. 使用 Redux

现在,我们已经构建了属于自己的 Redux,可以开始使用它来管理应用程序的状态了。

首先,我们需要创建一个 Store 实例,并传入 Reducer 和初始状态:

const store = new Store(todoReducer, []);

然后,我们可以使用 dispatch() 方法来分发 Action,并更新 Store 中的状态:

store.dispatch(addTodo('Learn Redux'));
store.dispatch(removeTodo(1));
store.dispatch(updateTodo(2, 'Understand Redux'));

最后,我们可以通过 getState() 方法来获取 Store 中的最新状态:

const state = store.getState();
console.log(state);

结语

通过从零实现一个 Redux,我们对 Redux 的原理有了更深入的了解。Redux 是一个强大的状态管理框架,可以帮助我们构建更易于理解和维护的应用程序。