Mobx

作者: 楼上那位 | 来源:发表于2017-05-06 10:25 被阅读113次

    autorun

    Autorun creates a reaction that runs once, and after that automatically re-runs whenever any observable data that was used inside the function changes.
    任何在aotorun中用到且被观察的数据发生变化,就会触发调用

    class ObservableTodoStore {
        @observable todos = [];
        @observable pendingRequests = 0;
    
        constructor() {
            mobx.autorun(() => console.log(this.report));
        }
    
        @computed get completedTodosCount() {
            return this.todos.filter(
                todo => todo.completed === true
            ).length;
        }
    
        @computed get report() {
            if (this.todos.length === 0)
                return "<none>";
            return `Next todo: "${this.todos[0].task}". ` +
                `Progress: ${this.completedTodosCount}/${this.todos.length}`;
        }
        addTodo(task) {
            this.todos.push({
                task: task,
                completed: false,
                assignee: null
            });
        }
    }
    
    observableTodoStore.addTodo("read MobX tutorial");
    observableTodoStore.addTodo("try MobX");
    observableTodoStore.todos[0].completed = true;
    observableTodoStore.todos[1].task = "try MobX in own project";
     observableTodoStore.todos[0].task = "grok MobX tutorial";
    
    

    第四行 observableTodoStore.todos[1].task = "try MobX in own project"; 并没有触发函数调用

    Because the report did not actually change as a result of the rename, although the backing data did. On the other hand, changing the name of the first todo did update the report, since that name is actively used in the report. This demonstrates nicely that not just the todos array is being observed by the autorun, but also the individual properties inside the todo items

    1 . Use the @observable decorator or observable(object or array) functions to make objects trackable for MobX.

    1. The@computed decorator can be used to create functions that can automatically derive their value from the state.
      3 . Useautorunto automatically run functions that depend on some observable state. This is useful for logging, making network requests, etc.
      4 . Use the@observerdecorator from the mobx-react package to make your React components truly reactive. They will update automatically and efficiently. Even when used in large complex applications with large amounts of data.

    相关文章

      网友评论

          本文标题:Mobx

          本文链接:https://www.haomeiwen.com/subject/npeetxtx.html