programing

반응 라우터 GoBack()이 제대로 작동하지 않음

prostudy 2022. 4. 2. 08:53
반응형

반응 라우터 GoBack()이 제대로 작동하지 않음

나는 문제에 직면했다.나는 라우팅에 반응-라우터-돔을 사용한다.잘 되고 있는데 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('/')이전 경로가 없도록 밀지 않고 교체하는 경우.

한 가지 가능한 방법은 링크를 사용하는 대신 history.push를 사용하여 경로를 동적으로 변경하십시오.링크 구성 요소를 제거하고 "li" 또는 "button"에서 onClick 이벤트를 정의하려면이제 먼저 onClick(클릭) 기능과 최종 사용 기록.push를 사용하여 다른 페이지에서 탐색할 경로 평균을 변경하십시오.

이것이 도움이 되었으면 좋겠다.

참조URL: https://stackoverflow.com/questions/54340143/react-router-goback-not-working-properly

반응형