代码森林饥人谷技术博客React.js学习

Mobx 十分钟快速入门

2018-08-24  本文已影响0人  Apolo_Du

Store, Redux 和 Mobx

Mobx 快速入门

通过下述的代码, 我们可以完成一个 react-mobx 实现的计数器. 点击这里查看实际效果.

安装依赖项: mobx, mobx-react

npm i mobx mobx-react

定义observable, observer 和 action

import {observable} from 'mobx';

let appState = observable({
    timer: 0
});
let App = observer(({ appState }) => {
    return (
        <div className="App">
            <h1>Time passed: {appState.timer}</h1>
        </div>
    );
});
setInterval(action(()=>{
  appState.timer +=1  
}), 1000) 

完整代码

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

// create State object
let appState = observable({ timer: 0 });

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

appState.resetTimer = action(() => {
    appState.timer = 0;
});

// create observer
let App = observer(({ appState }) => {
    return (
        <div className="App">
            <h1>Time passed
: {appState.timer}</h1>
            <button onClick={appState.resetTimer}>reset timer</button>
        </div>
    );
});

const root = document.getElementById("root");
ReactDOM.render(<App appState={appState} />, root);

参考

https://mobx.js.org/intro/overview.html

上一篇下一篇

猜你喜欢

热点阅读