gpt4 book ai didi

javascript - react 路由器 goBack() 无法正常工作

转载 作者:行者123 更新时间:2023-12-01 16:29:23 27 4
gpt4 key购买 nike

我遇到了一个问题。我使用 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>

最佳答案

这是因为您使用的是 history.replace('/') .您正在更换,而不是插入,因此没有以前的路线。

关于javascript - react 路由器 goBack() 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54340143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com