Reactガイドを読んでいくその252
これは
Reactのガイドを読んでいく記事です。
ガイドのリンク
クリーンアップを有する副作用
外部のデータソースへの購読をセットアップしたい場合、メモリリークが発生しないようにクリーンアップが必要。
メモリリークを避けるためにクリーンアップが必要なので、クリーンアップを有する物を使用する。
クラスを使った例
class FriendStatus extends React.Component { constructor(props) { super(props); this.state = { isOnline: null }; this.handleStatusChange = this.handleStatusChange.bind(this); } componentDidMount() { ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } handleStatusChange(status) { this.setState({ isOnline: status.isOnline }); } render() { if (this.state.isOnline === null) { return 'Loading...'; } return this.state.isOnline ? 'Online' : 'Offline'; } }
componentDidMountとcomponentWillUnmountとが双方にミラーのように対応していないといけない。
ライフサイクルメソッドを使うと2つのメソッドに書かれているコードが概念状は同一の副作用に関連してい流場合でも、
分割して書かないといけない。
明日はフックを使った例を見ていく。
今日はここまで。