我已升级到React路由器V4,现在正在与history.push
方法挣扎。ReactJS路由器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
但为什么?我的<BrowserRouter>
设置错误吗?
无论如何,感谢您的帮助:)
BrowserRouter在默认情况下具有隐式历史记录。你需要使用路由器。 参考:https://reacttraining.com/react-router/web/api/Router – Adriano
[如何在React Router v4中推送历史记录?](https://stackoverflow.com/questions/42701129/)如何推动历史在反应路由器v4) – lux