Reactjs React v4和Redux:在API调用后更新URL以显示新路由?

Reactjs React v4和Redux:在API调用后更新URL以显示新路由?,reactjs,redux,Reactjs,Redux,在我的React应用程序中,我试图在成功登录后将用户引导到“/”。如果可能,我需要在成功登录后将页面刷新为而不是。以下是我在需要调用API时使用的代码(当用户通过身份验证时,会发送相应的数据): 使用window.history.pushState({},null,resp.data)用于更改URL。但是,组件不会更新(我为/login、/signup和/)指定了BrowserRouter路由)。另外,window.location.replace(相应数据)刷新页面。有没有办法通过react来

在我的React应用程序中,我试图在成功登录后将用户引导到“/”。如果可能,我需要在成功登录后将页面刷新为而不是。以下是我在需要调用API时使用的代码(当用户通过身份验证时,会发送相应的数据):

使用
window.history.pushState({},null,resp.data)用于更改URL。但是,组件不会更新(我为/login、/signup和/)指定了BrowserRouter路由)。另外,
window.location.replace(相应数据)刷新页面。有没有办法通过react来实现这一点

您可以使用
react-router
包提供的HoC向组件中注入一些属性。您感兴趣的是
react router
中的历史对象,而不是窗口中的历史对象

import {withRouter} from 'react-router'

class MyComponent extends React.PureComponent {
  handleFormSubmit = event => {
    ...
    API.signin({
      ...
    }).then(resp => {
      if(resp.data) {
        const {history} = this.props
        history.push('/', {
          data
        })
      }
    })
  }
}

export default withRouter(MyComponent)

使用withRouter将使组件中的
{match,location,history}
对象可用。如果在
树中有
组件,使用上述模式,用户将被重定向到“/”路径。
数据将在
位置.state.data
上提供。(您需要使用
withRouter
包装您的主组件,并访问
位置
对象。

有条件地渲染react router的
组件。@sn42很抱歉,我仍在学习react的基础知识。要有条件地渲染a,是否需要在指定其他路由的位置指定此选项?)?。。。同时使用react路由器的
with router()
和而不是
窗口。历史记录
import {withRouter} from 'react-router'

class MyComponent extends React.PureComponent {
  handleFormSubmit = event => {
    ...
    API.signin({
      ...
    }).then(resp => {
      if(resp.data) {
        const {history} = this.props
        history.push('/', {
          data
        })
      }
    })
  }
}

export default withRouter(MyComponent)