【React.js】Twitter + Node + React.jsの勉強メモ
Build A Real-Time Twitter Stream with Node and React.js
チェックリスト
res.render('home', { markup: markup, // Pass rendered react markup state: JSON.stringify(tweets) // Pass current state to client side }); <section id="react-app">{{{ markup }}}</div> <script id="initial-state" type="application/json">{{{state}}}</script>
が
res.render('home', { state: JSON.stringify(tweets) // Pass current state to client side }); <section id="react-app"></div> <script id="initial-state" type="application/json">{{{state}}}</script>
これだけじゃダメなのか?
componentWillReceiveProps(newProps, oldProps)
の理解- This is not called for the initial render.
componentDidMount
の理解- Tweet取得時に、とりあえず
addTweet
でDOMをレンダリングするが、CSSでmax-height: 0px
として非表示にしている。
stateについて
State
はMutableな値を定義することが出来ます。一方でProps
はImmutableな値(I/F)です。- Stateは最低限に rootとなるComponentだけにStateを持たせて後は全部Propだけを持ってるImmutableなComponentにして、何か変更があるとrootのComponentでsetStateしてまとめてrerenderするような構成も可能だったりします。 親から子へ伝搬させるイメージ
- 基本的には
getIntialState
でstateの初期値を返して、データに変更があった場合にthis.setState
で更新します。 - そうするとComponentがrerenderされて表示が更新されます。子のComponentもrerenderされます。
Propsについて
- Propは基本的にはCompnentのattributeとして定義してComponentの中では
this.props.xxx
として参照する。それだけです。PropにはObjectでも関数でも何でも指定することが出来ます。
Anti pattern
In React, setting state via props is generally considered an anti-pattern. However when setting an initial state, and transferring a state from the server, this is not the case. Because the
getInitialState
method is only called before the first mount of our component, we need to use thecomponentWillReceiveProps
method to make sure that if we mount our component again, that it will receive the state