Mobx-React的TodoMVC

前言

由于鄙人最近在做项目用到React做UI和Mobx做数据控制处理。所以我就记录一下学习的东西。今天就分享一下自己做(抄)的一个小东西,那就是Todo List。

环境如下:

  • System: Ubuntu
  • node version: v8.0.0
  • npm version: 5.3.0
  • create-react-app version: 1.3.3

建立项目

我们用create-react-app my-app创建自己的项目,并进入自己的项目啦

create-react-app my-app
cd my-app

接下来安装mobx、mobx-react和一些组件

npm install mobx-react mobx --save
npm install mobx-react-devtools --save-dev
npm install direcctor --save

npm install todomvc-app-css todomvc-common --save

然后就:

npm start

居然成功了!太神奇啦!还以为会失败呢!

使用Decorator or not

首先呢,我们来看看github上面的人撕逼的内容:

  • Decorator is not supported!——撕逼1
  • Easily Add an Babel Plugin——撕逼2
  • why we don’t include them——撕逼3
  • you don’t need decorators——撕逼
  • the good time to have decorators now——撕逼4

大概内容这样吧:

撕逼精选:

  • if you use MobX or a similar library, you don’t need decorators. They are just syntax sugar in this case.
  • Since we don’t currently use decorators, we don’t take it upon ourselves to provide a migration path if the standard becomes incompatible.
  • We’re happy to support decorators after the spec advances, and they are officially supported in Babel without the -legacy plugin. And MobX works fine without decorators.
  • babel seems to now be off the -legacy plugin for 7.0 babel-plugin-transform-decorators

个人观点

  1. 确实decorators是个语法糖,但是不可否认decorators可以把复杂的代码变得清晰干净。因此我是很喜欢decorator(毕竟我是古老个javaer)。
  2. create-react-app的作者说道,他很开心看到有支持decorators的plugin,但是认为不太稳定、不太标准而且有decorators的替代品,所以先暂且不进行这方面的优化。
  3. 尽管现在有官方支持了,但create-react-app的还没动静。

综上所述

我暂且不在create-react-app的项目里面不用decorator,但假如你很想用的话,我推荐你看这篇文章How to get decorators in create-react-app(亲测可用)。

看完这个大家怎么想呢?无奈跟我一起做项目的朋友用了create-react-app建立项目,所以就出现这种尴尬的情况。


开始开发

1. Models

在src目录下创建一个models的目录,并创建TodoModels.js的文件。直接贴代码:

import { extendObservable } from 'mobx';

export default class TodoModel {
    store;
    id;
    title;
    completed;

    constructor(store, id, title, completed) {
        this.store = store;
        this.id = id;
        extendObservable(this, {
            title: title,
            completed: completed
        });
    }

    toggle() {
        this.completed = !this.completed;
    }

    destroy() {
        this.store.todos.remove(this);
    }

    setTitle(title) {
        this.title = title;
    }

    toJS() {
        return {
            id: this.id,
            title: this.title,
            completed: this.completed
        };
    }

    static fromJS(store, object) {
        return new TodoModel(store, object.id, object.title, object.completed);
    }
}

这里这特别的地方就是constructor()方法里面的内容啦。里面使用了extendObservable(),它跟ES当中的Object.assign很相似,也是把对象复制给target。但不同的就是这个observable了。从字面上可以理解,给target对象分配一个observable的属性变量。像代码里面,我把title: title分配给this这个对象,并且title变成一个observable的变量。而一开始声明的属性变量都是为了让大家清晰该类型有哪些属性。当然你也可以不加啦。

2. store

目录src/store

TodoStore.js

...
    constructor(props) {
        extendObservable(this, {
            todos: [],
            get activeTodoCount() {
                return this.todos.reduce(
                    (sum, todo) => sum + (todo.completed ? 0 : 1), 0
                )
            }
        });
    };

    subscribeServerToStore() {
        reaction(
            () => this.toJS(),
            todos => window.fetch && fetch('/api/todos', {
                method: 'post',
                body: JSON.stringify({ todos }),
                header: new Headers({ 'Content-Type': 'application/json'})
            })
        );
    }

    subscribeLocalstorageToStore() {
        reaction(
            () => this.toJS(),
            todos => localStorage.setItem('mobx-react-todomvc-todos', JSON.stringify({todos}))
        );
    }

...

这里特别的地方就是get activeTodoCount(){...}这个getter也变成一个computed的东西,还有reaction()用于产生副作用的东西,他第一个参数是产生数据的函数并且产生数据作为第二个函数输入参数,第二个参数是就是side effect啦。要注意的是里面执行的副作用访问的任何 observable 都不会被追踪。看来这个函数不是我们想要的action啊(可能这个项目还没有用到action)。迟点再抄一遍contactlist的demo吧。

3. component

目录src/component

TodoItem.js

import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import { expr, extendObservable } from 'mobx';

const ESCAPE_KEY = 27;
const ENTER_KEY = 13;

class TodoItem extends React.Component {
    editText;

    constructor(props) {
        super(props);
        extendObservable(this, {
            editText: ""
        });
    }

    render() {
        const {viewStore, todo} = this.props;
        return (
            
  • todo === viewStore.todoBeingEdited ? "editing" : "") ].join(" ")} >
  • ) } handleSubmit = (event) => { const val = this.editText.trim(); if (val) { this.props.todo.setTitle(val); this.editText = val; } else { this.handleDestroy(); } this.props.viewStore.todoBeingEdited = null; }; handleDestroy = () => { this.props.todo.destroy(); this.props.viewStore.todoBeingEdited = null; }; handleEdit = () => { const todo = this.props.todo; this.props.viewStore.todoBeingEdited = todo; this.editText = todo.title; }; handleKeyDown = (event) => { if (event.which === ESCAPE_KEY) { this.editText = this.props.todo.title; this.props.viewStore.todoBeingEdited = null; } else if (event.which === ENTER_KEY) { this.handleSubmit(event); } }; handleChange = (event) => { this.editText = event.target.value; }; handleToggle = () => { this.props.todo.toggle(); }; } TodoItem.propTypes = { todo: PropTypes.object.isRequired, viewStore: PropTypes.object.isRequired }; export default observer(TodoItem);

    这里又多了个observer的内容啦。observer函数可以用来将 React 组件转变成响应式组件。这里所说的响应式是指数据响应,而不是页面啊哈。简单来说:所有渲染 observable 数据的组件。 像这里我们使用了viewStore和todo两个有observable的变量,我们就必须使用observer否则在数据发生变化后,重新刷新组件。那有人说:我可以在最顶层定义observer啊,多么干净利落啊。很遗憾这样做是不行的。

    当 observer 需要组合其它装饰器或高阶组件时,请确保 observer 是最深处(第一个应用)的装饰器,否则它可能什么都不做。

    TodoApp.js

    class TodoApp extends React.Component {
        render() {
            const {todoStore, viewStore} = this.props;
            return (
                

    todos

    ) } componentDidMount() { var { Router } = require('director/build/director'); var viewStore = this.props.viewStore; var router = Router({ '/': function() { viewStore.todoFilter = ALL_TODOS; }, '/active': function() { viewStore.todoFilter = ACTIVE_TODOS; }, '/completed': function() { viewStore.todoFilter = COMPLETED_TODOS; } }); router.init('/'); } ... export default observer(TodoApp);

    这里我们通过路径来修改viewStore.todoFilter,进而对数据响应处理和组件刷新。这里加入了一个很有趣的devTool,看起来挺酷炫的开发组件。


    以上是我通过todo mvc学到的一些内容和感悟。希望大家喜欢。
    源码地址:https://github.com/Salon-sai/learning-mobx-react/tree/master/TodoList

    你可能感兴趣的:(Mobx-React的TodoMVC)