きょこみのーと

技術に関係ないほうのブログ

React.jsのチュートリアルをGoで動かしてみた

React.js入門しました。とりあえず動かしてみたレベル。

(とりあえず触る&ソース読んでよくわからない点とかメモってから、概要とか読む派なので。。。)

チュートリアルのexampleで用意されている言語はRuby, Node.js, Pythonしかありませんが、あえてGoでやります。


Goで起動する

チュートリアルソースコードgit cloneで取得します。

$ git clone https://github.com/reactjs/react-tutorial

プロジェクト直下にmain.goを作成します。(goji使ってます)

$ go get github.com/zenazn/goji

ソースコード

React.jsのチュートリアルをGoで書いてみたhttps://github.com/reac ...

あとは起動するだけ。

$ go run main.go

スクリーンショット 2015-02-01 15.54.26.png

なんかチャットっぽいやつのようだ。

色々触って動きを追って見る

サーバーのログを見るとわかるけど、2秒毎にGET:/comments.jsonが呼ばれている。

スクリーンショット 2015-02-01 15.57.02.png

それっぽいコードがある。

// public/scripts/example.js(126行目)
<CommentBox url="comments.json" pollInterval={2000} />,

このCommentBoxのComponentの実装は以下のようにajaxでGETしてsetStateでCommentBoxのrenderを行っている。

// public/scripts/example.js(29行目)
var CommentBox = React.createClass({
  // 2秒毎に呼ばれるやつ
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  // CommentBox子要素のCommentFormのPostボタンを押した時に呼ばれる
  handleCommentSubmit: function(comment) {
    var comments = this.state.data;
    comments.push(comment);
    this.setState({data: comments}, function() {
      // `setState` accepts a callback. To avoid (improbable) race condition,
      // `we'll send the ajax request right after we optimistically set the new
      // `state.
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: comment,
        success: function(data) {
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    });
  },
  // 初期呼び出し
  getInitialState: function() {
    return {data: []};
  },
  // TODO: これが2秒毎にajax呼ぶやつのトリガーっぽい?
  componentDidMount: function() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },
  // 表示更新(setStateで呼ばれる)
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm onCommentSubmit={this.handleCommentSubmit} />
      </div>
    );
  }
});

CommentBoxは子要素にCommentListとCommentFormを持っていて、setStatusで渡されたdataでrenderを呼び出している。

また、CommentFormのPostボタンを押したは、親要素からpropsでもらったonCoomentSubmitのfunctionを呼び出して、ajaxでPOST:/comments.jsonを呼び出している。

呼び出し後のrenderの流れは2秒毎に呼んでいる方と同じ。

おわり

とりあえず動かしてみて、その後に概要を読んでReact.jsの良さがわかってきた気がする。

英語が苦手な方は、こちらを読むといいと思います!!!とてもわかりやすいです!

一人React.js Advent Calendar 2014 - Qiita