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

发布于 2022-09-11 16:44:23 字数 2345 浏览 17 评论 0

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"
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文