![](/img/trans.png)
[英]history.push(path) is not working in react-router-dom v4, with redux while redirecting to 404
[英]ReactJS Router V4 history.push not working
我已經升級到 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>
設置錯誤嗎??
無論如何,感謝您的幫助:)
您必須{withRouter} from 'react-router-dom'
導入{withRouter} from 'react-router-dom'
並以這種方式導出您的課程
export default withRouter(Cars)
嘗試將 forceRefresh={true} 添加到您的 BrowserRouter。
<BrowserRouter forceRefresh={true}>
使用 v4 你必須使用this.context.history.push('/cart');
查看這些帖子以獲取更多見解:
這對我有用:
routes.js
import React from 'react';
import { Route, Switch, Redirect } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
const routes = (
<div>
<BrowserRouter>
<Switch>
<Route path="/login" component={Login} />
<Route path="/home" component={Logged} />
</Switch>
</BrowserRouter>
</div>
);
Login.js
componentWillReceiveProps = nextProps => {
const { signedIn, history } = this.props;
if (signedIn !== nextProps.signedIn && nextProps.signedIn) {
history.push('/home');
}
};
export default withRouter(connect(mapStateToProps)(Login));
現在它將呈現! 希望它對某人有幫助
嘗試使用 props 中的歷史記錄並確保您的導出使用 withRouter 包裝。
前任:
this.props.history.push('/test')
export default withRouter(TestComponent)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.