【问题标题】:history.push doesn't redirecthistory.push 不重定向
【发布时间】:2018-11-24 10:07:11
【问题描述】:

使用 react-router v4 和 BrowserRouter 我正在调用 history.push 导航到不同的路径。不幸的是,浏览器中的 url 发生了变化,但没有导航。我不确定作曲路线是否正确,还是我错过了什么?

<Route render={({history}) =>
    <div className="nav" onClick={() => {history.push('/new-route');}}><i 
    className="fa fa-user"/></div>}
/>

【问题讨论】:

  • 更新:我试过props.history.push("/new-route");,但没有乐趣
  • 你试过withRouter吗?
  • 是的,我做到了(我不知道有任何其他方法可以生成props.history

标签: reactjs react-router-dom


【解决方案1】:

您可以尝试使用上下文 api

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      // context.history.push === history.push
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

【讨论】:

  • 感谢您的帮助!不幸的是,结果是一样的。浏览器 url 已更改,但要使重定向正常工作,我需要添加 location.reload()
猜你喜欢
  • 1970-01-01
  • 2018-07-15
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2021-07-10
  • 2020-11-23
  • 2021-02-07
相关资源
最近更新 更多