表題がわけわからないかもですが、やりたいことは
-
react-router
を使用している(今回とは関係ないけど、redux-router
も使用している) - ルーティングで
/notifications
,/notifications/unread
,/notifications/official
みたいにあったときに、表示するコンポーネントは同一のものを使用したい - それぞれのパスで画面遷移したときに、それぞれに相応しいAPIを初期処理として呼びたい
みたいな感じです。ルーティングの設定のところは、そもそもこの書き方がイケてるのかまだわかっていないのですが、以下のような感じです
routeの設定
<Route path='notification' component={NotificationComponent} >
<IndexRoute />
<Route path='unread' />
<Route path='official' />
</Route>
バージョン情報
- react :
0.14.0
- react-dom :
0.14.0
- react-router :
1.0.0-rc1
- redux :
3.0.2
- react-redux :
2.1.2
- redux-router :
1.0.0-beta3
同一のコンポーネントにしないのであれば・・・
それぞれのコンポーネントのcomponentDidMount
でfetch
の処理をすればいいだけ
NotificationAll.js
componentDidMount() {
store.dispatch(Actions.fetchAllNotifications())
}
NotificationUnread.js
componentDidMount() {
store.dispatch(Actions.fetchUnreadNotifications())
}
何も考えず同一のコンポーネントにすると・・・
/notifications
から/notifications/unread
に遷移したときに、componentDidMount
は呼ばれないため、fetch
の処理が走らない。
または、componentDidUpdate
なんかで呼び出すようにしたら、これはAPIの処理でstate
を更新すると思うので、大抵の場合は無限ループになってしまう
componentDidUpdate() {
store.dispatch(Actions.fetchNotifications())
}
react-router
のComponent Lifecycle
というページに載っていた。
とはいえ、どういうパターンでの遷移か(子コンポーネントを表示する遷移なのかとか)でフックするイベントが異なるので思ったより複雑。
今回の自分のケースだと、
NotificationComponent.js
componentDidMount() {
this.fetch();
}
componentDidUpdate (prevProps) {
if (prevProps.location.pathname !== this.props.location.pathname) {
this.fetch();
}
}
fetch() {
// ...
}
こんな感じで、path
を比較してるところはイケてないと思うのですが、最初にリストアップしたやりたいことはとりあえずできた