为何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"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论