react-router 페이지로 돌아 가기 기록을 어떻게 구성합니까?

누구든지 특정 경로가 아닌 이전 페이지로 돌아가는 방법을 알려주시겠습니까?

이 코드를 사용하는 경우 :

var BackButton = React.createClass({

 mixins: [Router.Navigation],
  render: function() {
    return (
        <button
            className="button icon-left"
            onClick={this.navigateBack}>
            Back
        </button>
    );
  },

  navigateBack: function(){
    this.goBack();
  }
});

이 오류가 발생했습니다. 라우터 기록이 없기 때문에 goBack ()이 무시되었습니다.

내 경로는 다음과 같습니다.

// Routing Components
Route = Router.Route;
RouteHandler = Router.RouteHandler;
DefaultRoute = Router.DefaultRoute;

var routes = (
 <Route name="app" path="/" handler={OurSchoolsApp}>
     <DefaultRoute name="home" handler={HomePage} />
     <Route name="add-school" handler={AddSchoolPage}  />
     <Route name="calendar" handler={CalendarPage}  />
     <Route name="calendar-detail" path="calendar-detail/:id" handler={CalendarDetailPage} />
     <Route name="info-detail" path="info-detail/:id" handler={InfoDetailPage} />
     <Route name="info" handler={InfoPage} />
     <Route name="news" handler={NewsListPage} />
     <Route name="news-detail" path="news-detail/:id" handler={NewsDetailPage} />
     <Route name="contacts" handler={ContactPage} />
     <Route name="contact-detail" handler={ContactDetailPage} />
     <Route name="settings" handler={SettingsPage} />
 </Route>
 );

 Router.run(routes, function(Handler){
   var mountNode = document.getElementById('app');
   React.render(<Handler /> , mountNode);
 });



답변

다음과 같이 초기화하여 라우터에서 BrowserHistory를 활성화하면됩니다 <Router history={new BrowserHistory}>.

그 전에 다음 BrowserHistory에서 요구해야합니다 .'react-router/lib/BrowserHistory'

도움이 되었기를 바랍니다.

업데이트 : ES6의 예

const BrowserHistory = require('react-router/lib/BrowserHistory').default;

const App = React.createClass({
    render: () => {
        return (
            <div><button onClick={BrowserHistory.goBack}>Go Back</button></div>
        );
    }
});

React.render((
    <Router history={BrowserHistory}>
        <Route path="/" component={App} />
    </Router>
), document.body);


답변

React v16 및 ​​ReactRouter v4.2.0으로 업데이트 (2017 년 10 월) :

class BackButton extends Component {
  static contextTypes = {
    router: () => true, // replace with PropTypes.object if you use them
  }

  render() {
    return (
      <button
        className="button icon-left"
        onClick={this.context.router.history.goBack}>
          Back
      </button>
    )
  }
}

React v15 및 ReactRouter v3.0.0으로 업데이트 (2016 년 8 월) :

var browserHistory = ReactRouter.browserHistory;

var BackButton = React.createClass({
  render: function() {
    return (
      <button
        className="button icon-left"
        onClick={browserHistory.goBack}>
        Back
      </button>
    );
  }
});

임베디드 iframe을 사용하여 좀 더 복잡한 예제로 바이올린을 만들었습니다 : https://jsfiddle.net/kwg1da3a/

React v14 및 ReacRouter v1.0.0 (2015 년 9 월 10 일)

다음과 같이 할 수 있습니다.

var React = require("react");
var Router = require("react-router");

var SomePage = React.createClass({
  ...

  contextTypes: {
    router: React.PropTypes.func
  },
  ...

  handleClose: function () {
    if (Router.History.length > 1) {
      // this will take you back if there is history
      Router.History.back();
    } else {
      // this will take you to the parent route if there is no history,
      // but unfortunately also add it as a new route
      var currentRoutes = this.context.router.getCurrentRoutes();
      var routeName = currentRoutes[currentRoutes.length - 2].name;
      this.context.router.transitionTo(routeName);
    }
  },
  ...

돌아가는 데 필요한 이력이 있는지주의해야합니다. 페이지를 직접 클릭 한 다음 다시 클릭하면 앱 이전의 브라우저 기록으로 돌아갑니다.

이 솔루션은 두 시나리오를 모두 처리합니다. 그러나 뒤로 버튼을 사용하여 페이지 내에서 탐색하고 브라우저 기록에 추가 할 수있는 iframe은 처리하지 않습니다. 솔직히 나는 그것이 react-router의 버그라고 생각합니다. 여기에 생성 된 문제 : https://github.com/rackt/react-router/issues/1874


답변

  1. 수입 withRouter

    import { withRouter } from 'react-router-dom';
  2. 구성 요소를 다음과 같이 내 보냅니다.

    export withRouter(nameofcomponent) 
  3. 예를 들어 버튼을 클릭하면 다음을 호출합니다 goBack.

    <button onClick={this.props.history.goBack}>Back</button>

react-router-domv4.3에서 테스트 됨


답변

this.context.router.goBack()

내비게이션 믹스 인이 필요하지 않습니다!


답변

반응 라우터, 상태 비 저장 기능을 사용하는 믹스 인이없는 ES6 방법.

import React from 'react'
import { browserHistory } from 'react-router'

export const Test = () => (
  <div className="">
    <button onClick={browserHistory.goBack}>Back</button>
  </div>
)


답변

React Hooks 사용

수입:

import { useHistory } from "react-router-dom";

상태 비 저장 구성 요소 :

  let history = useHistory();

이벤트

history.goBack()


답변

React-router v4 Live Example 과 함께 React 16.0을 사용한 작업 예제를 확인하십시오 . 코드 Github 확인

사용 withRouterhistory.goBack()

이것이 내가 구현하는 아이디어입니다 …

History.js

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import './App.css'


class History extends Component {

  handleBack = () => {
    this.props.history.goBack()
  }

  handleForward = () => {
    console.log(this.props.history)
    this.props.history.go(+1)
  }

  render() {
    return <div className="container">
      <div className="row d-flex justify-content-between">
        <span onClick={this.handleBack} className="d-flex justify-content-start button">
          <i className="fas fa-arrow-alt-circle-left fa-5x"></i>
        </span>
        <span onClick={this.handleForward} className="d-flex justify-content-end button">
          <i className="fas fa-arrow-alt-circle-right fa-5x"></i>
        </span>
      </div>
    </div>
  }
}

export default withRouter(History)

PageOne.js

import React, { Fragment, Component } from 'react'

class PageOne extends Component {

   componentDidMount(){
      if(this.props.location.state && this.props.location.state.from != '/pageone')
      this.props.history.push({
         pathname: '/pageone',
         state: {
             from: this.props.location.pathname
         }
       });
   }

   render() {
      return (
         <Fragment>
            <div className="container-fluid">
               <div className="row d-flex justify-content-center">
                  <h2>Page One</h2>
               </div>
            </div>
         </Fragment>
      )
   }
}

export default PageOne

추신 코드가 여기에 모두 게시하는 것이 큰 죄송합니다.