我已升级到 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
但为什么?是我<BrowserRouter>
设置错了吗??
无论如何,感谢您的帮助:)