返回

Rematch core 组件简介

前端

前言

在上一篇文章中,我们对 rematch 的代码结构进行了概述。今天,我们将继续深入研究 rematch 的核心组件——rematch core。

Rematch core 组件

Rematch core 是 rematch 的核心库,它包含了 rematch 的基本功能,如状态管理、动作管理和副作用管理。rematch core 的主要组成部分包括:

  • Store: 存储应用程序状态的对象。
  • Action: 表示状态改变意图的对象。
  • Reducer: 负责处理动作并更新状态的函数。
  • Effect: 负责处理副作用的函数。
  • Plugin: 用于扩展 rematch 功能的插件。

示例代码

以下是一个使用 rematch core 创建简单计数器的示例代码:

import { createStore } from "rematch";

// 定义初始状态
const initialState = {
  count: 0,
};

// 定义动作
const actions = {
  increment: (state) => {
    return { count: state.count + 1 };
  },
  decrement: (state) => {
    return { count: state.count - 1 };
  },
};

// 定义归约器
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return actions.increment(state);
    case "DECREMENT":
      return actions.decrement(state);
    default:
      return state;
  }
};

// 创建存储
const store = createStore({
  models: {
    counter: {
      state: initialState,
      reducers: reducer,
      actions,
    },
  },
});

// 订阅状态变化
store.subscribe(() => {
  console.log(store.getState());
});

// 派发动作
store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "DECREMENT" });

结语

本文简要介绍了 rematch core 组件的组成和功能。如果您想更深入地了解 rematch core,可以参考 rematch 的官方文档。