react-router go back a page how do you configure history?

前端 未结 21 1304
说谎
说谎 2020-11-30 18:30

Can anyone please tell me how I can go back to the previous page rather than a specific route?

When using this code:

var BackButton = React.createCla         


        
21条回答
  •  难免孤独
    2020-11-30 18:58

    Check out my working example using React 16.0 with React-router v4 Live Example. check out the code Github

    Use withRouter and history.goBack()

    This is the idea I am implementing...

    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 
    } } 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 (
             
                

    Page One

    ) } } export default PageOne

    p.s. sorry the code is to big to post it all here

提交回复
热议问题