美文网首页
mobx && mobx-react入门demo

mobx && mobx-react入门demo

作者: coffee1949 | 来源:发表于2019-07-20 16:00 被阅读0次
    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 (    
                <div className="App">
                    <h1>Time passed: {appState.timer}</h1>
                    <button onClick={appState.resetTimer}>reset timer</button>
                </div>
            );
        }
    );
    
    const root = document.getElementById("root");
    // 敲黑板,下面通过属性把appStare传递过去了
    ReactDOM.render(<App appState={appState} />, 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 (    
                <div className="App">
                    <h1>Time passed: {appState.timer}</h1>
                    <button onClick={appState.resetTimer}>reset timer</button>
                </div>
            );
        }
    );
    
    const root = document.getElementById("root");
    // 敲黑板,下面通过属性把appStare传递过去了
    // 这里添加了appState属性,所以class App内部使用的也是appState
    // 如果这里添加的属性是store呢,class App内部使用什么呢???
    ReactDOM.render(<App appState={appState} />, root);
    

    相关文章

      网友评论

          本文标题:mobx && mobx-react入门demo

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