mobx && mobx-react入门demo

import React from "react";
import ReactDOM from "react-dom";
import { observable, action } from "mobx";
import { observer } from "mobx-react";

// create State objectlet 
const appState = observable({ timer: 0 });

// define action
setInterval(
    action(() => {
        appState.timer += 1;
    }),
    1000
);
appState.resetTimer = action(() => {
    appState.timer = 0;
});

// create observerlet 
const App = observer(
    // 敲黑板,这里是一个js代码,要加上花括号
    ({ appState }) => {    
        return (    
            

Time passed: {appState.timer}

); } ); const root = document.getElementById("root"); // 敲黑板,下面通过属性把appStare传递过去了 ReactDOM.render(, root);

添加注释

import React from "react";
import ReactDOM from "react-dom";
import { observable, action } from "mobx";
import { observer } from "mobx-react";

// create State objectlet 
const appState = observable(    // 只是使用了observable()包裹了下
    { timer: 0 }
);

// define action
setInterval(
    action(     // 只是使用了action()包裹了下
        () => {
            appState.timer += 1;
        }
    ),
    1000
);
appState.resetTimer = action(   // 使用action()包裹下
    () => {
        appState.timer = 0;
    }
);

// create observerlet 
const App = observer(
    // 函数定义组件,传递appState代替props
    // 这里使用了花括号包裹?
    ({ appState }) => {    
        return (    
            

Time passed: {appState.timer}

); } ); const root = document.getElementById("root"); // 敲黑板,下面通过属性把appStare传递过去了 // 这里添加了appState属性,所以class App内部使用的也是appState // 如果这里添加的属性是store呢,class App内部使用什么呢??? ReactDOM.render(, root);

你可能感兴趣的:(mobx && mobx-react入门demo)