[英]react-router (v4) how to go back?
試圖弄清楚我怎樣才能回到上一頁。 我正在使用[react-router-v4][1]
這是我在第一個登錄頁面中配置的代碼:
<Router>
<div>
<Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
<Route exact path="/" component={Page1}/>
<Route path="/Page2" component={Page2}/>
<Route path="/Page3" component={Page3}/>
</div>
</Router>
為了轉發到后續頁面,我只需執行以下操作:
this.props.history.push('/Page2');
但是,我怎樣才能回到上一頁呢? 嘗試了下面提到的一些事情,但沒有運氣: 1. this.props.history.goBack();
給出錯誤:
TypeError:null 不是對象(評估“this.props”)
this.context.router.goBack();
給出錯誤:
TypeError:null 不是對象(評估“this.context”)
this.props.history.push('/');
給出錯誤:
TypeError:null 不是對象(評估“this.props”)
在下面發布Page1
代碼:
import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
class Page1 extends Component {
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
}
handleNext() {
this.props.history.push('/page2');
}
handleBack() {
this.props.history.push('/');
}
/*
* Main render method of this class
*/
render() {
return (
<div>
{/* some component code */}
<div className="navigationButtonsLeft">
<Button onClick={this.handleBack} bsStyle="success">< Back</Button>
</div>
<div className="navigationButtonsRight">
<Button onClick={this.handleNext} bsStyle="success">Next ></Button>
</div>
</div>
);
}
export default Page1;
我認為問題在於綁定:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this); // i think you are missing this
}
goBack(){
this.props.history.goBack();
}
.....
<button onClick={this.goBack}>Go Back</button>
正如我在您發布代碼之前假設的那樣:
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this); // you are missing this line
}
更新:
現在我們有了鈎子,所以我們可以使用useHistory輕松完成
const history = useHistory()
const goBack = () => {
history.goBack()
}
return (
<button type="button" onClick={goBack}>
Go back
</button>
);
原帖:
this.props.history.goBack();
這是 react-router v4 的正確解決方案
但是你應該記住的一件事是你需要確保 this.props.history 存在。
這意味着你需要調用這個函數this.props.history.goBack();
<Route/>包裹的組件內部
如果您在組件樹中更深的組件中調用此函數,它將不起作用。
編輯:
如果你想在組件樹中更深的組件中擁有歷史對象(它沒有被 <Route> 包裹),你可以這樣做:
...
import {withRouter} from 'react-router-dom';
class Demo extends Component {
...
// Inside this you can use this.props.history.goBack();
}
export default withRouter(Demo);
與 React Router v4 和 dom-tree 中任何位置的功能組件一起使用。
import React from 'react';
import { withRouter } from 'react-router-dom';
const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;
export default withRouter(GoBack);
這里的每個答案都有整體解決方案的一部分。 這是我用來讓它在比使用 Route 更深的組件內部工作的完整解決方案:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
^ 您需要第二行來導入函數並導出頁面底部的組件。
render() {
return (
...
<div onClick={() => this.props.history.goBack()}>GO BACK</div>
)
}
^ 需要箭頭函數而不是簡單的 onClick={this.props.history.goBack()}
export default withRouter(MyPage)
^ 用 'withRouter()' 包裹你的組件名稱
這是您可以處理這個問題的最干凈和最簡單的方法,它也消除了this keyword
的可能陷阱。 使用功能組件:
import { withRouter } from "react-router-dom";
用withRouter()
HOC
包裝你的component
或更好的App.js
這使得history
在“應用程序范圍”可用。 包裝您的組件只會使history available for that specific
組件``` 您的選擇。
所以你有:
export default withRouter(App);
在 Redux 環境export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );
你甚至應該能夠通過這種方式從你的動作創建者那里獲得用戶history
。
在您的component
執行以下操作:
import {useHistory} from "react-router-dom";
const history = useHistory(); // do this inside the component
goBack = () => history.goBack();
<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>
export default DemoComponent;
Gottcha useHistory
僅從最新的 v5.1 react-router-dom
導出,因此請務必更新包。 但是,您不必擔心。 關於this keyword
的許多障礙。
您還可以將其設為可重用組件以在您的應用程序中使用。
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}```
Cheers.
你能提供你使用this.props.history.push('/Page2');
的代碼嗎this.props.history.push('/Page2');
?
您是否嘗試過 goBack() 方法?
this.props.history.goBack();
它列在這里https://reacttraining.com/react-router/web/api/history
這里有一個活生生的例子https://reacttraining.com/react-router/web/example/modal-gallery
如果使用反應鈎子,只需執行以下操作:
import { useHistory } from "react-router-dom";
const history = useHistory();
history.go(-1);
嘗試:
this.props.router.goBack()
只需使用
<span onClick={() => this.props.history.goBack()}>Back</span>
掛鈎版本(反應16.8+):
最低版本。
import { useHistory } from "react-router-dom";
export const Item = () => {
let history = useHistory();
return (
<>
<button onClick={() => history.goBack()}>Back</button>
</>
);
};
希望這會幫助某人:
import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';
interface Props {
history: History;
}
@withRouter
export default class YourComponent extends React.PureComponent<Props> {
private onBackClick = (event: React.MouseEvent): void => {
const { history } = this.props;
history.goBack();
};
...
也許這可以幫助某人。
我使用history.replace()
重定向,所以當我嘗試使用history.goBack()
,我被發送到我正在使用的頁面之前的上一頁。 所以我將方法history.replace()
更改為history.push()
以便可以保存歷史記錄並且我可以返回。
我不確定其他人是否遇到過這個問題或者可能需要看到這個。 但我花了大約 3 個小時試圖解決這個問題:
我想通過單擊按鈕實現一個簡單的 goBack()。 我以為我開了個好頭,因為我的 App.js 已經被包裹在路由器中,我正在從“react-router-dom”導入 { BrowserRouter as Router }; ... 因為 Router 元素允許我評估歷史對象。
例如:
import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Header />
<Route path='/' component={Splash} exact />
<Route path='/home' component={Info} exact />
<Route path='/timer' component={Timer} exact />
<Route path='/options' component={Options} exact />
<Footer />
</Router>
);
}
export default App;
但是問題出在我的 Nav(一個子組件)模塊上,我不得不從 'react-router-dom' 'import { withRouter };' 然后強制導出:
export default withRouter(Nav);
例如:
import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
render() {
return (
<div>
<label htmlFor='back'></label>
<button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
<label htmlFor='logOut'></label>
<button id='logOut' ><a href='./'>Log-Out</a>
</button>
</div>
);
}
}
export default withRouter(Nav);
總之,withRouter 是由於 React 中的一個已知問題而創建的,在某些情況下,當拒絕從路由器繼承時,強制導出是必要的。
您可以在功能組件中使用history.goBack()
。 就像這樣。
import { useHistory } from 'react-router';
const component = () => {
const history = useHistory();
return (
<button onClick={() => history.goBack()}>Previous</button>
)
}
navigate(-1)
從歷史記錄中省略當前頁面:
navigate(-1, { replace: true })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.