わたしも見ている | JavaScript芸人もりたけんじ

【React/Redux】わたしもみている | Container Components

【React/Redux】わたしもみている | Container Components

Container Components | @chantastic

【Redux】ReactやるにもAngularやるにもとにかくRedux
【Redux】ReactやるにもAngularやるにもとにかくRedux

記事はこのコードについて悪くはないがReactの利点を見逃していると述べています。

[code language="javascript"]
// CommentList.js
class CommentList extends React.Component {
constructor() {
super();
this.state = { comments: [] }
}
componentDidMount() {
$.ajax({
url: "/my-comments.json",
dataType: 'json',
success: function(comments) {
this.setState({comments: comments});
}.bind(this)
});
}
render() {
return

<ul> {this.state.comments.map(renderComment)} </ul>

;
}
renderComment({body, author}) {
return

<li>{body}—{author}</li>

;
}
}

[/code]

これをContainerとComponentを分ける。
なぜ分けるか
・データフェッチとレンダリングの関心を分ける→読みやすいとか保守しやすい
・再利用性が高まる
・型定義を使える(PropsType)

Container
→fetchして子コンポーネントに渡すだけ。stateを扱う

Component
→子コンポーネントはrenderするだけ。propsを扱う

Data structure
Your markup components should state expectations of the data they require. PropTypes are great for this.

コンポーネントはコンテナーからどんなデータが期待されて渡ってくるかを前もってPropTypesとして書いておくことで予想できてバグを見つけられたり、学習コストを下げるのですね。

コンテナー

[code language="javascript"]
// CommentListContainer.js
class CommentListContainer extends React.Component {
constructor() {
super();
this.state = { comments: [] }
}
componentDidMount() {
$.ajax({
url: "/my-comments.json",
dataType: 'json',
success: function(comments) {
this.setState({comments: comments});
}.bind(this)
});
}
render() {
//CommentListとして切り出す。
return <CommentList comments={this.state.comments} />;
}
}
[/code]

コンポーネント

[code language="javascript"]
// CommentList.js
class CommentList extends React.Component {
constructor(props) {
super(props);//props継承する
}
render() {
return

<ul> {this.props.comments.map(renderComment)} </ul>

;
}
renderComment({body, author}) {
return

<li>{body}—{author}</li>

;
}
}
[/code]

これはgoodだそうです。
ただ「この記事」に言わせるとここからが本番らしいです。
※「この記事」はReduxのチュートリアルにリンクされている記事で、リンク先の「Presentational and Container Components」文中で、Reduxを学ぶ上で一読すべき記事として書かれています。

ちょっと今日はここまで

でわーー

reference
Container Components | @chantastic

【関連記事】
【React】Reactの動きを理解したい人の為の最小サンプル

【React入門】過去のREACT初心者の自分にpropsとstateの違いを簡単に説明してあげたい

【React × ECMAScript2015 × Flux】を手っ取り早く学びたい人の為にサンプル作ったよ【3の倍数と3が付くときだけ猫になるカウンター】

React × Flux × ECMAScript2015 LINE風チャット

他のReact記事

フロントエンド記事

GitHub

qiita