reatc-router を
リソース更新の
[TOC]
前提
react、
react@16.2.0 react-router-dom@4.2.2
同一ページの リソース更新方法
ルーテイング
ルーテイングは、以下の 通りです。
"/posts/:slug"
に該当する ページから、 同じく 該当する ページへ 遷移する 際、 リソースの 更新が 行えるようにしたいです。 <Switch> <Route exact path="/" component={PostList}/> <Route exact path="/posts" component={PostList}/> <Route exact path="/posts/:slug" component={PostDetail}/> <Route exact path="/about" component={About}/> <Route component={NoMatch}/> </Switch>
当初の
実装
componentWillMount
で、リソースの 取得を 行なっていましたが、 同一ページ遷移時は、 既に Component は マウント済に なるのか、 componentWillMount
が呼び出されず、 リソースの 取得が 行われなかったです。 componentWillMount() { this.props.fetchPost(this.props.match.params.slug); }
同一ページ更新時に、
リソースの 取得を 行う
componentWillReceiveProps
を追加し、 ページの locatioin 変化時に、 リソースの 再取得を 行うようにしました。 試していないですが、componentWillMount() { this.props.fetchPost(this.props.match.params.slug); } componentWillReceiveProps(nextProps) { if (nextProps.location !== this.props.location) { this.props.fetchPost(nextProps.match.params.slug); } }
componentDidUpdate
に実装しても 同様の ことは 実施できそうです。
スクロール位置の 移動
componentWillReceiveProps
で
この
react-router に
と
インストール
npm i -S react-router-scroll-memory
実装 (エラーに なった)
Doument をUncaught Error: A <router > may have only one child element
と
<scrollmemory ></scrollmemory>
の
import文の
追加 import ScrollMemory from 'react-router-scroll-memory';
Router の
下に ScrollMemory
を追加 // -------------------------------------------- // ReactDOM.render // ------------ ReactDOM.render( <Provider store={store}> <BrowserRouter> <ScrollMemory /> <Route path="/" component={Main}/> </BrowserRouter> </Provider> , document.getElementById("root"));
実装 (うまく いった )
以下のように
の 直上に、 ScrollMemory
を追加 <div className="body"> <Navbar toggle={this.drawerToggle}/> <ScrollMemory /> <Switch> <Route exact path="/" component={PostList}/> <Route exact path="/posts" component={PostList}/> <Route exact path="/posts/:slug" component={PostDetail}/> <Route exact path="/about" component={About}/> <Route component={NoMatch}/> </Switch> </div>
参考
以下、
javascript - Reload a route that has state based on query params using React Router - Stack Overflow
【react-router】
react-router v4で
React.jsの
以上です。
taion/react-router-scroll: React Router scroll management と
いうのも ありましたが、 react-router v4 だと 使えなさそうでした。 ↩
コメント