我遇到了一个问题。我使用react-router-dom进行路由。它运行良好,但goBack无法正常运行。当我单击“后退”按钮时,它首先进入NotFound
/ Signin
页,然后重定向到后页。我该如何克服这个问题?
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import Signin from '../ui/signin/Signin';
import AddEvent from '../ui/events/AddEvent';
import EventView from '../ui/events/EventView';
import NotFound from '../ui/NotFound';
const history = createBrowserHistory();
const privatePages = [
'/events',
'/addevent',
];
const publicPages = ['/', '/signup','/forgotpassword'];
const onEnterPublicPage = () => {
if (Meteor.userId()) {
history.replace('/events');
}
};
const onEnterPrivatePage = () => {
if (!Meteor.userId()) {
history.replace('/');
}
};
export const onAuthenticationChange = (isAuthenticated) => {
const pathname = this.location.pathname;
const isUnauthenticatedPage = publicPages.includes(pathname);
const isAuthenticatedPage = privatePages.includes(pathname);
if (isAuthenticated && isUnauthenticatedPage) {
history.replace('/events');
} else if (!isAuthenticated && isAuthenticatedPage) {
history.replace('/');
}
}
export const routes = (
<Router history = {history}>
<Switch>
<Route
exact path="/events"
component={ListEvents}
onEnter={onEnterPrivatePage} />
<Route
exact path="/addevent"
component={AddEvent}
onEnter={onEnterPrivatePage} />
<Route component={NotFound}/>
<Route
exact path="/"
component={Signin}
onEnter={onEnterPublicPage} />
</Switch>
</Router>
);
在组件中:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this);
}
goBack(){
this.props.history.goBack();
// this.props.history.push.go(-1);
}
返回
<Link
to=""
onClick={this.goBack}
className="back-icon">
Back
</Link>
答案 0 :(得分:0)
这是因为您正在使用history.replace('/')
。您正在更换,而不是在推,所以没有以前的路线。
答案 1 :(得分:0)
一种可能的方法是,不使用Link,而使用history.push动态更改路由。为此,删除Link组件并在“ li”或“ button”上定义onClick事件。现在,首先执行onClick函数中的所有任务,最后使用history.push更改要在其他页面上导航的路线。
我希望这对您有帮助