2017-08-03 125 views
1

我有以下組成部分觸發事件操作時返回按鈕被點擊陣營

class NewCampaign extends Component { 
    constructor(props) { 
    super(props) 
    this.nextStep = this.nextStep.bind(this) 
    this.previousStep = this.previousStep.bind(this) 

    this.state = { 
     page: 1, 
    } 
    } 

    nextStep() { 
     var newStep = this.state.step +1; 
     this.setState({ page: newStep }) 
    } 

    previousStep() { 
     var newStep = this.state.step -1; 
     this.setState({ page: newStep }) 
    } 


    render() { 
    return (
     <div className="campaign"> 
      {page === 1 && <Step1Page nextStep={this.nextStep}/>} 
      {page === 2 && <Step2Page previousStep={this.previousStep} nextStep={this.nextStep}/>} 
      {page === 5 && <Step5Page previousStep={this.previousStep} />}        
     </div> 

    ) 
    } 
} 

目前,每個組件步驟頁有2個按鈕:上一個和下一個按鈕,當被點擊將更新狀態稱爲頁面。

這工作正常。但是,現在有一個請求使瀏覽器上的Back Button轉到上一步。

我不確定我是否可以使用browser history,因爲我仍處於相同的路線上。唯一改變的是名爲page的組件狀態,它由兩個動作nextStep和PreviousStep觸發。

有沒有辦法找出什麼時候點擊後退按鈕並激活previousStep操作?

回答

-2

假設使用的是反應-路由器,就可以聽到的變化:https://github.com/ReactTraining/history

相關片之中:

// Listen for changes to the current location. 
const unlisten = history.listen((location, action) => { 
    // location is an object like window.location 
    console.log(action, location.pathname, location.state) 
}) 

動作是PUSH之一,替換或POP取決於用戶如何獲得當前URL。

相關問題