在 index.js
中直接 push 或 throw dispatch 效果很好:
...
import { push } from 'react-router-redux'
const browserHistory = createBrowserHistory()
export const store = createStore(
rootReducer,
applyMiddleware(thunkMiddleware, routerMiddleware(browserHistory))
)
// in v5 this line is deprecated
export const history = syncHistoryWithStore(browserHistory, store)
history.push('/any') // works well
store.dispatch(push('/any')) // works well
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>
), document.getElementById('root'))
App.js
class App extends Component {
render() {
return (
<div className="app">
<Switch>
<Route path="/" component={Main} />
<Route path="/any" component={Any} />
</Switch>
</div>
);
}
}
export default withRouter(connect(/*...*/)(App))
但在 redux-thunk
操作中,所有尝试都以重写 url 结束,但没有重新呈现
...
export function myAction(){
return (dispatch) => {
// fetch something and then I want to redirect...
history.push('/any') // change url but not re-render
dispatch(push('/any')) // change url but not re-render
store.dispatch(push('/any')) // change url but not re-render
}
}
这个 myAction
正在内部调用 fetch() 并且应该在成功后重定向。
如果我在组件内部运行 this.props.history.push('/any')
,它就可以工作!但我需要在成功 fetch()
我试图用 withRouter
或 Route
包装所有组件,但没有帮助。
最佳答案
将 history
对象注入(inject)到您的组件中并像这样使用推送:
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
@withRouter
@connect(({auth})=>({auth}))
class App extends Component {
// on redux state change
componentWillReceiveProps(nextProps) {
if(!nextProps.auth)
this.props.history.push('/login')
}
render() {
return (
<div>
<Button
// on button click
onClick={this.props.history.push('/')}
>
Home page
</Button>
</div>
);
}
}
关于reactjs - redux-react-route v4/v5 push() 在 thunk Action 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45020768/