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

本文共 4017 字,大约阅读时间需要 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/

    你可能感兴趣的文章
    Node.js卸载超详细步骤(附图文讲解)
    查看>>
    Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
    查看>>
    Node.js安装及环境配置之Windows篇
    查看>>
    Node.js安装和入门 - 2行代码让你能够启动一个Server
    查看>>
    node.js安装方法
    查看>>
    Node.js的循环与异步问题
    查看>>
    Node.js高级编程:用Javascript构建可伸缩应用(1)1.1 介绍和安装-安装Node
    查看>>
    NodeJS @kubernetes/client-node连接到kubernetes集群的方法
    查看>>
    Nodejs express 获取url参数,post参数的三种方式
    查看>>
    nodejs http小爬虫
    查看>>
    nodejs libararies
    查看>>
    nodejs npm常用命令
    查看>>
    NodeJS 导入导出模块的方法( 代码演示 )
    查看>>
    nodejs 的 Buffer 详解
    查看>>
    nodejs 读取xlsx文件内容
    查看>>
    nodejs 运行CMD命令
    查看>>
    nodejs-mime类型
    查看>>
    NodeJs——(11)控制权转移next
    查看>>
    NodeJS、NPM安装配置步骤(windows版本)
    查看>>
    NodeJS、NPM安装配置步骤(windows版本)
    查看>>