【问题标题】:React router goBack() not working properly反应路由器 goBack() 无法正常工作
【发布时间】:2019-06-17 19:18:57
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs meteor react-router react-router-dom


    【解决方案1】:

    一种可能的方法是,不使用 Link,而是使用 history.push 动态更改路由。要实现这一点,请删除 Link 组件并在“li”或“button”上定义 onClick 事件。现在首先执行 onClick 函数中的所有任务,最后使用 history.push 更改路由意味着在其他页面上导航。

    希望对你有帮助

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我要把history.replace('/')替换成history.push('/')吗?
      • 您可以尝试使用history.push('/'),然后使用goBack
      • 我使用 goBack 像 `goBack(){ this.props.history.goBack(); }`。对吗?
      • 对不起,它不起作用。我添加了组件代码。请看这个。
      • 您可以查看history 的文档。另请查看example
      猜你喜欢
      • 2017-11-09
      • 1970-01-01
      • 2017-03-15
      • 2020-08-26
      • 2019-05-08
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多