ReactJS v4 路由

ReactJS v4 routing

我想知道如何在 Onclick 事件中更改组件到目前为止我遇到了这些并且 none 它们有效

1)this.props.history.push('/')

导致此错误:无法读取未定义的 属性 'push'

2)this.context.router.history.push('/')

导致此 error:Cannot 读取 属性 'history' of undefined

3)this.context.history.push('/')

导致未定义error:Cannot读取属性'push'

4)using BrowserRouter

这似乎在 React v4 中不可用,所以这不是解决方案

5)creating new instance of sth with the name of hash history and then using that object push method

这会导致像 myurl.com/#/navigatelink 这样的事情,url 中的 # 会毁掉一切

6) using window.location.href

这会导致刷新并重新加载不需要的页面

7)creating new instance of BrowserHistory from history/createBrowserHistory

在我的浏览器 url 中工作正常,预计会出现 url,但组件不会更改,这次我必须手动按 f5 并刷新页面

所以你能告诉我我应该如何使用 onclick 事件导航到其他页面或组件而不刷新 react v4 中的页面

您可以单独从 history 包导入 createHistory 并创建您自己的 history 对象实例,您将其传递给 Router 组件,您可以在您认为合适的任何地方使用它应用

例子

import { Router, Route, Switch } from "react-router-dom";
import createHistory from "history/createBrowserHistory";

const history = createHistory();

class App extends React.Component {
  render() {
    return (
      <main>
        <Router history={history}>
          <button onClick={() => history.push('/')}> Click me </button>
          {/* ... */}
        </Router>
      </main>
    );
  }
}

你有没有使用 withRouter HOC 来确保 react router props 确实被传递到你的组件?听起来这并没有发生。注销路线正下方的道具,并确保在必要时将道具向下传递。你也可以在你想要道具的组件上使用 withRouter HOC,它会注入它们。