ST8*_*T80 18 reactjs react-router react-router-v4
我已升级到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"));
Run Code Online (Sandbox Code Playgroud)
然后我有另一个文件,在那里我添加了一个简单的返回到某个页面,如下所示:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我无法弄清楚这里出了什么问题.当我点击按钮时,URL会变为/但都是.有人可以帮助我吗?
编辑
我发现,当我这样做时它起作用:
this.props.history.push('/home')
Run Code Online (Sandbox Code Playgroud)
和
<button onClick={this.onNavigateHome.bind(this)}
Run Code Online (Sandbox Code Playgroud)
但似乎不知何故?
当我做
this.context.history.push('/home')
Run Code Online (Sandbox Code Playgroud)
我明白了Cannot read property 'context' of null为什么?我的<BrowserRouter>设置错了吗?
无论如何,谢谢你的帮助:)
您必须以{withRouter} from 'react-router-dom'这种方式导入和导出您的类
export default withRouter(Cars)
小智 9
尝试将 forceRefresh={true} 添加到您的 BrowserRouter。
<BrowserRouter forceRefresh={true}>
Run Code Online (Sandbox Code Playgroud)
小智 1
对于 v4,您必须this.context.history.push('/cart');
查看这些帖子以获得更多见解:
使用 BrowserRouter 时,history.push 不起作用
| 归档时间: |
|
| 查看次数: |
26255 次 |
| 最近记录: |