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