2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactJS + Flumpt のカウンターのサンプルその2

Last updated at Posted at 2016-07-01

目的

以前書いたサンプルを書き直してみた

ファイル構成

.
├── dest
│   └── app.js
├── index.html
├── package.json
└── src
    └── app.jsx

package

pacage.json
{
  "devDependencies": {
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babelify": "^7.3.0",
    "browserify": "^13.0.1",
    "flumpt": "^0.2.0",
    "flux": "^2.1.1",
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "watchify": "^3.7.0"
  },
  "dependencies": {},
  "scripts": {
    "watch": "watchify src/app.jsx -o dest/app.js -v --debug"
  },
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "es2015",
            "react"
          ]
        }
      ]
    ]
  }
}

実行

$ npm install
$ npm run build
$ npm run watch

code

src/app.jsx
'use strict';

import * as React from 'react';  //eslint-disable-line
import {Flux, Component} from 'flumpt';
import {render} from 'react-dom';


class CounterComponent extends Component {
  render() {
    return (
      <div>
        <p>count: {this.props.count}</p>
        <div>
          <button onClick={() => this.dispatch('counter', {num: 1})}>+1</button>
          <button onClick={() => this.dispatch('counter', {num: -1})}>-1</button>
        </div>
      </div>
    );
  }
}


class App extends Flux {
  subscribe() {
    this.on('counter', value => {
      this.asyncWait(1000).then(() => {
        this.update(state => {
          state.count += value.num;
          return state;
        });
      });
    });
  }

  render(state) {
    return <CounterComponent {...state}/>;
  }

  asyncWait(msec) {
    return Promise.resolve(msec)
      .then(msec => {
        const currentTimeMsec = new Date().getTime();
        while (new Date().getTime() < currentTimeMsec + msec);
      });
  }
}


const app = new App({
  renderer: el => {
    render(el, document.querySelector('.js-container'));
  },
  initialState: {count: 0},
  middlewares: [
    // logger
    (state) => {
      console.log(state);
      return state;
    }
  ]
});

app.update(_initialState => _initialState);

表示

$ python -m SimpleHTTPServer 8000

スクリーンショット 2015-11-07 14.48.21.png

メモ

  • whatwg-fetch で api たたくことを想定して asyncWait 関数作って値を遅れて取る感じにしてみた

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?