专栏名称: 1歩
WEB 前端开发工程师
目录
相关文章推荐
脚本之家  ·  大厂都在用的 12 大主流 AI ... ·  12 小时前  
脚本之家  ·  大厂都在用的 12 大主流 AI ... ·  12 小时前  
前端大全  ·  突发!美国对中国断供 EDA。网友:真卡脖子 ·  4 天前  
前端大全  ·  蔚来面试题:计算白屏时间 ·  4 天前  
51好读  ›  专栏  ›  1歩

MobX入门 TodoList

1歩  · 掘金  · 前端  · 2018-06-28 08:02

正文

请到「今天看啥」查看全文


"babel": {
    "plugins": [
        "transform-decorators-legacy"
    ],
    "presets": [
        "react-app"
    ]
}

创建 App 的 store

Mobx 中创建 store 的常见关键字如下: observable computed action
observable 用来声明可观察的数据、 computed 是声明可观察数据的演变数据,和 observable 具有同等地位, action 用来改变 observable 数据,但是 action 不是必须的,可以认为其是较好的约定,最好遵循。在 mobx 程序中使用 class 装饰器 是最佳实践,因此我们的代码也使用装饰器实现。

import {observable, computed, action} from 'mobx';

class Todo {
    // 定义一个 TODO 项目的类,id 是随机数,没有使用@observable 装饰可以理解为是只读的
    id = Math.random();
    // todo 的 title 及完成状态 finished 是可被观察及更新的,同时 finished 的初始状态为 false
    @observable title;
    @observable finished = false;
    // 构造函数接收tile
    constructor(title) {
        this.title = title;
    }
}

// TODO List 类
class TodoList {
    // 可被观察的待办项 todos
    @observable todos = [];
    // 计算属性,重可观察属性 todos 衍生出来,返回没有完成的待办项的个数
    @computed get unfinishedTodoCount() {
        return this.todos.filter(todo => !todo.finished).length;
    }
    // 动作用来更新 todos 属性的值,添加待办项
    @action
    addTodo = title => {
        if (!title) return;
        this.todos.push(new Todo(title));
    }
}

// 我们创建TodoList 对象,在手动的添加两个待办项,此处的 store 对象可以理解为是一个单例,在将其引用暴露出去
const store = new TodoList();
store.todos.push(new Todo('Get Coffee'), new Todo('Write blog'));
store.todos[0].finished = true;

export default store;

实现监听数据的组件

Provider observer inject 均为是mobx-react提供。







请到「今天看啥」查看全文