仿写 redux 源码(一)

226 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

redux 是什么

  • redux 是一个用来帮助我们管理应用状态的工具库
  • 它以集中式 store 的方式对整个应用的状态进行集中管理
  • 它制定了一套数据更新的规则,使得应用中的状态只能以可预测的方式进行更新

redux 的数据流向

  • redux 初始化一个 store 来集中管理视图页面的状态数据
  • 页面渲染时,可以直接在 store 中获取状态
  • store 中的 reducer 是一个纯函数,它定义了更新状态的规则
  • 当用户在页面视图中进行一些操作,想要更新数据时,就需要 dispatch 一个 action 来更新状态 state,action 是一个纯对象,其中包含 type 与 payload
  • reducer 函数会接收 action 和更新之前的 state,并根据 action 来更新 state,最后返回更新之后的 state
  • 最后 redux 在 state 更新之后,触发页面更新渲染

redux 的使用

创建 store

// redux
// import { applyMiddleware, combineReducers, createStore } from "redux";
// import logger from "redux-logger";
// import thunk from "redux-thunk";
// import promise from "redux-promise";

import {
  createStore,
  applyMiddleware,
  combineReducers,
  logger,
  thunk,
  promise,
  promiseFull,
} from "../my-redux";

const countReducer = (state = 100, action) => {
  const { type, payload = 1 } = action;

  switch (type) {
    case "ADD":
      return state + payload;
    default:
      return state;
  }
};

const countReducer2 = (state = { num: 1 }, action) => {
  const { type, payload = 1 } = action;

  switch (type) {
    case "ADD2":
      return { ...state, num: state.num + payload };
    default:
      return state;
  }
};

export const store = createStore(
  countReducer,

  // 合并多个 reducer
  // combineReducers({
  //   count: countReducer,
  //   count2: countReducer2,
  // }),
  applyMiddleware(promise, thunk, logger)
);
  • 代码示例中
    • countReducer 是一个 reducer 纯函数,定义了 state 的修改规则
    • applyMiddleware 函数见名知意,就是用来应用中间件的方法,其返回一个 enhancer 函数
    • createStore 是 redux 提供的一个用来创建 store 的方法
      • 其接收的第一个参数就是 reducer 函数,可以是 combineReducers 方法的执行结果

      • 第二个参数就是 store 的初始数据

      • 第三个参数 enhancer 就是 applyMiddleware 的返回值

小结

  • 本文大致介绍了 redux 是什么,redux 的数据流向,以及 redux 创建 store 的方法

  • 后面的文章,我们将继续深入 redux 源码中,学习其精妙的实现原理

  • 今天的分享就到这里了,欢迎大家在评论区里面进行讨论 👏。

  • 如果觉得文章写的不错的话,希望大家不要吝惜点赞,大家的鼓励是我分享的最大动力 🥰