LoginSignup
4
3

More than 5 years have passed since last update.

react-router@v4 + Redux でPostした後に一覧ページにリダイレクトするが、レンダリングされなくて苦労したときのメモ

Posted at

背景

react-router + Redux でCRUD操作後のリダイレクトで躓いた。例えば、新規作成が成功したあとは、一覧ページにリダイレクトしてほしい。 react-router@v4でのリダイレクトが結構面倒で、やりかたによってはレンダリングがされなくて困ったのでメモ。

解決方法

基本的にはreact-routerでのリダイレクトは、historyモジュールを使ったやり方がオーソドックスっぽい。

参考: history.push not working when using BrowserRouter

Root.js


import React from 'react'
import { Provider } from 'react-redux'
import ListMemo from '../containers/ListMemo'
import CreateMemo from '../containers/CreateMemo'
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'
import PropTypes from 'prop-types'
import history from './History'

const Root = ({ store }) => (
  <Provider store={store}>
    <Router history={history}>
      <div>
        <Route exact path="/" component={ListMemo} />
        <Route path="/create" component={CreateMemo} />
      </div>
    </Router>
  </Provider>
)

Root.propTypes = {
  store: PropTypes.object.isRequired
}

export default Root

Hisotry.js

import {createBrowserHistory} from 'history'

export default createBrowserHistory()

CreateMemo.js

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import {
  createMemo,
} from '../actions'

class CreateMemo extends Component {
  // ===略=====

  handleSubmit(e) {
    e.preventDefault();
    const { dispatch } = this.props
    dispatch(createMemo(this.state)).then(e => {
      this.props.history.push('/') // ここでcreateのactionが終わった後でpushする
    })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Name:
            <input type="text" name="name" value={this.state.name} onChange={this.handleChangeName} />
            Description:
            <input type="text" name="description" value={this.state.description} onChange={this.handleChangeDescription}/>
          </label>
          <input type="submit" value="Submit" />
        </form>
      </div>
    )
  }
}

// ==略

うまく行かなかった方法

はじめはactionの中でresponseが返ってきたときに history.push('/') していた。ブラウザのURLはリダイレクトしたが、レンダリングされなかった。原因は不明。念の為、うまくいかなかったときに参考にしたリンクもメモしておく↓

Best practice to redirect within action creator?

4
3
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
4
3