reactjs - redux-react-route v4/v5 push() 在 thunk Action 中不起作用

标签 reactjs react-router redux-thunk react-router-redux

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()

之后在 thunk 操作中运行重定向

我试图用 withRouterRoute 包装所有组件,但没有帮助。

最佳答案

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/

相关文章:

ios - React Native 和 Firebase 错误 403

reactjs - 外部api上任何前缀的CORS都需要400 header

reactjs - Uncaught Error : useNavigate() may be used only in the context of a <Router> component

reactjs - React Router v4 多个查询字符串

react-router - 错误刷新路由器 react 路由器

reactjs - 使用 redux thunk 测试异步操作

javascript - 类型错误 : middleware is not a function in store

javascript - React - 处理动态内联样式的理想方式

javascript - 处理 expo react native 中的多个复选框

javascript - 如何在异步调度完成后执行组件中的方法(thunk 或 Action 创建者)?