返回

用Javascript亲手打造一个精简版的Redux框架,带你玩转状态管理

前端

前言

Redux是一个用于管理应用程序状态的开源JavaScript库,它遵循Flux设计模式,被广泛应用于构建前端Web应用。Redux的核心思想是将应用程序的状态集中存储在一个可预测的store中,并通过dispatch函数触发action,由reducer函数处理action并更新store中的状态。

Redux的核心概念

store

Redux中的store是一个对象,它包含了应用程序的当前状态。store中的数据是只读的,任何对store的修改都必须通过dispatch函数来触发。

dispatch

dispatch函数用于触发action,action是一个对象,它包含了要执行的操作以及相关的数据。dispatch函数将action传递给reducer,reducer根据action来更新store中的状态。

reducer

reducer是一个函数,它接受一个action和一个旧的state,并返回一个新的state。reducer必须是纯函数,这意味着它不能修改任何外部变量,也不能产生副作用。

中间件

中间件是Redux中可选的组件,它可以在dispatch函数和reducer之间插入额外的逻辑。中间件可以用于日志记录、异步操作、错误处理等。

实现一个精简版的Redux框架

createStore

首先,我们来实现一个创建store的函数createStore,它接收一个reducer函数作为参数,并返回一个store对象。

function createStore(reducer) {
  let state = reducer(undefined, {});
  const listeners = [];

  const getState = () => state;

  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach((listener) => listener());
  };

  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter((l) => l !== listener);
    };
  };

  return { getState, dispatch, subscribe };
}

使用createStore创建一个store

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

const store = createStore(reducer);

使用dispatch和getState操作store

store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // 1

store.dispatch({ type: 'DECREMENT' });
console.log(store.getState()); // 0

使用中间件

const loggerMiddleware = (store) => (next) => (action) => {
  console.log('dispatching', action);
  const result = next(action);
  console.log('next state', store.getState());
  return result;
};

const storeWithMiddleware = createStore(reducer, [loggerMiddleware]);

storeWithMiddleware.dispatch({ type: 'INCREMENT' });

结语

通过本文,我们实现了简化版本的Redux框架,并探讨了Redux的基本原理和应用。Redux是一个强大的状态管理工具,它可以帮助你构建可预测且易于维护的前端应用程序。希望本文能让你对Redux有更深入的理解,并帮助你在实际项目中应用它。