【问题标题】:ReactJS Router V4 history.push not workingReactJS Router V4 history.push 不工作
【发布时间】:2017-09-02 21:33:16
【问题描述】:

我已升级到 React Router V4,现在正在努力使用 history.push 方法。

我有一个 index.js 文件:

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

import { Main} from "./components/Main";
import { About } from "./components/About";
import { Cars} from "./components/Cars";


class App extends React.Component {

render() {
    return (
        <BrowserRouter history={history}>

            <div>
                <Route path={"/"} component={Main} />
                <Route path={"/cars"} component={Cars}/>
                <Route path={"/about"} component={About}/>
            </div>
        </BrowserRouter>
    )
  }
}

render(<App/>, window.document.getElementById("app"));

然后我有另一个文件,我在其中添加了一个简单的返回到某个页面,如下所示:

import React from "react";
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

export class Cars extends React.Component {
  navigateBack() {
    history.push('/')
  }

  render() {
    return(
        <div>
            <h3>Overview of Cars</h3>
            <p>Model: </p>
            <button onClick={this.navigateBack} className="btn btn-primary">Back</button>
        </div>
    )
  }
}

所以,我无法弄清楚这里出了什么问题。当我单击该按钮时,URL 更改为/,但仅此而已。有没有人可以帮帮我?

编辑

我发现,当我这样做时它会起作用:

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

<button onClick={this.onNavigateHome.bind(this)}

但这似乎有点不对劲??

当我这样做时

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

我收到Cannot read property 'context' of null 但为什么呢?我的&lt;BrowserRouter&gt; 设置错了吗??

无论如何,谢谢你的帮助:)

【问题讨论】:

标签: reactjs react-router react-router-v4


【解决方案1】:

对于 v4,您必须使用 this.context.history.push('/cart');
查看这些帖子了解更多信息:

How to push to History in React Router v4?

history.push not working when using BrowserRouter

【讨论】:

  • 奇怪 - 这不起作用,尽管我的研究给了我相同的答案。我找到了一个解决方案,但它似乎是错误的。我已经编辑了我的帖子,所以说清楚。也许你知道解释?
  • 我使用 v4,但我没有 this.context.history
【解决方案2】:

你必须以这种方式导入{withRouter} from 'react-router-dom'并导出你的类

export default withRouter(Cars)

【讨论】:

  • 临时 withRouter 是从 react-router 导入的,而不是从 react-router-dom 导入的。更多信息请查看withRouter
【解决方案3】:

尝试将 forceRefresh={true} 添加到您的 BrowserRouter。

<BrowserRouter forceRefresh={true}>

【讨论】:

  • 这可能不是一个好方法,但不知道为什么。
【解决方案4】:

尝试使用 props 中的历史记录,并确保您的导出使用 withRouter 进行包装。

例如:

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


export default withRouter(TestComponent)

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2018-06-08
    • 2018-01-21
    • 2018-07-08
    • 2019-06-15
    • 2020-03-08
    • 2019-04-29
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多