9
9

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.

connected-react-routerを使ってhandlerでルーティングをしよう!

Last updated at Posted at 2019-05-24

Reactjsでの開発では、
reactとreduxを一緒に使うことが多いと思います。

routingは、react-router-domというライブラリを使うのが簡単ですが、一緒に
connected-react-routerで、routingも一緒にstoreで管理するのがいいと思います。
react-router-reduxは、公式でdeprecatedになっているのでこちらを使うのが良いでしょう。

redux-thunkも必要みたいです。

link以外の画面推移方法が英語しかなかったので、記録のために

pushを使って、onClickなどのhandlerでroutingをできるようにします。

#shell
yarn add react-router-dom react-redux redux connected-react-router

action等はとりあえず省略します。
##index.jsx


import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from "redux"
import { Provider } from "react-redux"
import thunk from "redux-thunk"
import { createBrowserHistory } from "history"
import { routerMiddleware, ConnectedRouter } from 'connected-react-router'
import { Switch } from "react-router-dom"
import rootReducers from "./reducers"

const history = createBrowserHistory()

const store = createStore(
  rootReducers(history),
  applyMiddleware(
    thunk,
    routerMiddleware(history),
  )
)

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <App />
      </Switch>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

##reducer.js

import { combineReducers } from "redux"
import { connectRouter } from 'connected-react-router'

export default history => combineReducers({
  router: connectRouter(history),
  //.....ここに他のreducerを
})

##App.jsx

connected-react-routerpushをdispatchしてルーティングするのが良いと思います



import React from 'react';
import { Route } from "react-router-dom"
import { connect } from "react-redux"
import { push } from "connected-react-router"

const App = () => {
  return(
  <React.Fragment>
    <Route path='/top' component={TopContainer} />
    <Route path='/second' component={Second} />
  </React.Fragment>
)}

const Top = props => (
  <button onClick={props.pushClicked}>button</button>
)
const Second = () => (
  <p>second page</p>
)

const mapDispatchToProps = {
  pushClicked: () => dispatch(push("/second")),
}
const TopContainer = connect(null, mapDispatchToProps)(Top)

動作確認をしていないので間違っていたら教えてください!
あと、わかんなかったら言ってください!

9
9
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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?