15
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React Router v4の変更点

Posted at

スクリーンショット 2017-04-23 11.13.26.png

React Routerのバージョンが4になっていろいろ変わっていました。

公式ページも変わってました。
https://reacttraining.com/react-router/web/guides/quick-start

import

以前はreact-routerからimportする仕様でしたが、v4はwebとnativeが分かれるようになりました。
webの場合はreact-router-domから、nativeはreact-router-nativeからimportする仕様に変更されています。

// v3
import { Route } from 'react-router'

// v4 : web
import { Route } from 'react-router-dom'
// v4 : native
import { Route } from 'react-router-native'

Router

Routerも大幅な仕様の変更が行われています。
個人的にはv4の方がスッキリしていて好きです。

// v3
import React from 'react'
import { render } from 'react-dom'
import { 
  Router, 
  Route, 
  IndexRoute, 
  IndexLink,
  browserHistory 
} from 'react-router';

render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <IndexRoute component={Top} />
      <Route path='hoge' component={Hoge} />
    </Route>
  </Router>
)

// v4
import React from 'react'
import { render } from 'react-dom'
import {
  Route,
  BrowserRouter
} from 'react-router-dom'

render(
  <BrowserRouter>
    <div>
      <Route exact={true} path='/' component={Top}/>
      <Route path='hoge' component={Hoge}/>
    </div>
  </BrowserRouter>
)

パラメーターの受け取り方

パラメーターの受け取り方も変更されました。
今まではprops直下に値が入っていましたが、v4はmatchの中にパラメーターが入っています。

// v3
import React, { Component } from 'react'

class Hoge extends Component {
  constructor(props) {
    super(props);
    // this.props.paramsにパラメーターが格納
    const params = this.props.params
  }

  render() {
    return (
      <div>Hoge</div>
    )
  }
}

// v4
import React, { Component } from 'react'

class Hoge extends Component {
  constructor(props) {
    super(props);
    // パラメーターはthis.props.match内に変更
    const params = this.props.match.params
  }

  render() {
    return (
      <div>Hoge</div>
    )
  }
}

まとめ

他にも変更点はあると思いますが、一旦自分が修正した変更をざっくりまとめました
破壊的な変更もあるので、v3で作ったものを無理やり乗せかえる必要はないと思います。

15
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?