为何connected-react-router + redux-thunk异步跳转路由,遇到重定向时会无法正常跳转并且栈溢出?

connected-react-router + redux-thunk异步跳转路由,遇到重定向时会不停修改地址并导致栈溢出:
问题代码:
<Redirect exact from="/" to="/home" /> + setTimeout(() => dispatch(push('/')), 1e3)
错误截图:
图片描述

组件详情:

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions/counter'
import { push } from 'connected-react-router';

const Counter = (props) => (
  <div>
    Counter: {props.count}
    <button onClick={props.increment}>+</button>
    <button onClick={props.decrement}>-</button>
    <button onClick={props.back}>back</button>
  </div>
)

Counter.propTypes = {
  count: PropTypes.number,
  increment: PropTypes.func.isRequired,
  decrement: PropTypes.func.isRequired,
}

const mapStateToProps = state => ({
  count: state.count,
})

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch(increment()),
  decrement: () => dispatch(decrement()),
  back: () => {
    setTimeout(() => dispatch(push('/')), 1e3)
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Counter)

路由配置:

import React from 'react'
import { Route, Switch, Redirect } from 'react-router'
import Home from '../components/Home'
import Hello from '../components/Hello'
import Counter from '../components/Counter'
import NoMatch from '../components/NoMatch'
import NavBar from '../components/NavBar'

const routes = (
  <div>
    <NavBar />
    <Switch>
      <Redirect exact from="/" to="/home" />
      <Route path="/home" component={Home} />
      <Route path="/hello" component={Hello} />
      <Route path="/counter" component={Counter} />
      <Route component={NoMatch} />
    </Switch>
  </div>
)

export default routes

环境:

"dependencies": {
    "connected-react-router": "^6.0.0",
    "history": "^4.7.2",
    "prop-types": "^15.6.2",
    "react": "^16.6.0",
    "react-dom": "^16.6.0",
    "react-redux": "^6.0.0",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0"
  }
阅读 3.3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏