博客
关于我
MobX 学习 - 06 异步任务、rootStore、数据监测
阅读量:389 次
发布时间:2019-03-05

本文共 3931 字,大约阅读时间需要 13 分钟。

MobX 异步数据加载与 Redux 比较

在 React 应用中,处理异步任务是一个常见的挑战。Redux 和 MobX 都提供了处理异步数据的方法,但它们各有优劣。以下将详细介绍如何在 MobX 中实现异步数据加载,并与 Redux 的异步处理进行对比。

Redux 与 MobX 异步处理的对比

Redux 异步处理 - Thunk 中间件

Redux 提供了一个名为 Thunk 的中间件,可以用来在 reducers 中定义异步操作。通过使用 dispatch 函数,可以将 actions 组合成一个 thunk 函数,这个函数可以执行异步操作,例如 API 请求,并在完成后通过 dispatch 发送一个 action 更新状态。

MobX 异步处理 - Saga 或 Thunk 中间件

MobX 提供了两种异步处理方法:SagaThunk。MobX 的 Thunk 和 Redux 的 Thunk 有相似之处,但 MobX 的 Saga 更加强大,支持更复杂的异步操作,包括并发和错误处理。

使用 MobX 实现异步数据加载

配置远端请求

  • 安装必要的依赖
  • npm install json-server axios
    1. 创建 JSON 数据文件
    2. ./src/todo.json{  "todos": [    { "id": 1, "title": "React", "completed": false },    { "id": 2, "title": "Angular", "completed": false },    { "id": 3, "title": "Vue", "completed": false }  ]}
      1. 安装 Axios
      2. npm install axios

        创建 loadTodos 异步任务

        TodoListStore 类

        import { makeObservable, observable, action, computed, runInAction } from "mobx";import TodoViewStore from "./TodoViewStore";import axios from "axios";class TodoListStore {  todos = [];  filter = "all";  constructor(todos) {    if (todos) this.todos = todos;    makeObservable(      this,      {        todos: observable,        filter: observable,        createTodo: action,        deleteTodo: action,        clear: action.bound,        changeFilter: action.bound,        unCompletedTodoCount: computed,        filterTodos: computed      }    );    this.loadTodos();  }  async loadTodos() {    const todos = await axios.get("http://localhost:3005/todos").then(response => response.data);    runInAction(() => this.todos.push(...todos.map(todo => new TodoViewStore(todo.title))));  }}

        RootStore 统一管理

        import TodoListStore from "./TodoStore/TodoListStore";import CounterStore from "./CounterStore/CounterStore";import { createContext, useContext } from "react";class RootStore {  constructor() {    this.counterStore = new CounterStore();    this.todoListStore = new TodoListStore();  }}const RootStoreContext = createContext();const RootStoreProvider = ({ store, children }) => (  
        {children}
        );const useRootStore = () => useContext(RootStoreContext);export { RootStore, RootStoreProvider, useRootStore };

        组件开发

        TodoFooter 组件

        import { observer } from "mobx-react-lite";import { useRootStore } from "../../stores/RootStore";import { useTodoListStore } from "../../stores/TodoStore/TodoListStore";function TodoFooter() {  const { todoListStore } = useRootStore();  const { filter, changeFilter } = todoListStore;  return (    
        {todoListStore.unCompletedTodoCount} item left
        );}export default observer(TodoFooter);

        使用 autorun 进行数据监测

        import { observer } from "mobx-react-lite";import { useEffect } from "react";import { autorun } from "mobx";import axios from "axios";function TodoHeader() {  const [title, setTitle] = useState("");  const { todoListStore } = useRootStore();  const handleAddTodo = (e) => {    if (e.key === "Enter") {      todoListStore.createTodo(title);      setTitle("");    }  };  return (    

        todos

        setTitle(event.target.value)} onKeyUp={handleAddTodo} />
        );}export default observer(TodoHeader);

        MobX 异步操作的注意事项

        远端请求中的数据转换

        loadTodos 方法中,使用 runInAction 将异步操作包裹在一个 Action 中执行,以确保在 MobX 环境下正确更新状态。

        MobX 异步数据的监测

        MobX 提供了 autorun 方法,可以用来监控状态的变化。例如,在 TodoHeader 组件中,可以使用 autorun 来跟踪 todoListStore 的状态变化。

        MobX 的优化配置

        为了避免 ESLint 警告,可以在项目根目录下创建 .eslintrc.js 文件:

        module.exports = {  plugins: ["react-hooks"],  rules: {    "react-hooks/exhaustive-deps": 0  }};

        总结

        在 MobX 中,通过 runInAction 方法,可以在异步操作完成后触发一个 Action,用于更新状态。这与 Redux 的 Thunk 中间件类似,但 MobX 提供了更强大的异步控制能力。通过合理使用 autorunreaction 方法,可以实现对状态的精细监测和响应。在实际开发中,合理配置 ESLint 并通过提供必要的上下文,可以确保组件的高效运行和良好的代码质量。

    转载地址:http://ytbzz.baihongyu.com/

    你可能感兴趣的文章
    invalid byte sequence for encoding
    查看>>
    技术美术面试问题整理
    查看>>
    ORB-SLAM2:LoopClosing线程学习随笔【李哈哈:看看总有收获篇】
    查看>>
    Codeforces Round #305 (Div. 1) B. Mike and Feet(单调栈)
    查看>>
    js求阶乘
    查看>>
    Making the grade 和Sonya and Problem Wihtout a Legend
    查看>>
    Nginx---惊群
    查看>>
    项目中常用的审计类型概述
    查看>>
    (九)实现页面底部购物车的样式
    查看>>
    python-day3 for语句完整使用
    查看>>
    基于LabVIEW的入门指南
    查看>>
    weblogic之cve-2015-4852
    查看>>
    Java注释
    查看>>
    C++ 函数重载
    查看>>
    使用mybatis-generator生成底层
    查看>>
    Mybatis【5】-- Mybatis多种增删改查那些你会了么?
    查看>>
    计算输入的一句英文语句中单词数
    查看>>
    lvs+keepalive构建高可用集群
    查看>>
    6 个 Linux 运维典型问题
    查看>>
    Failed to get D-Bus connection: Operation not permitted解决
    查看>>