1. ホーム
  2. javascript

[解決済み] react-router (v4) どうしたら戻れるのか?

2022-08-24 21:59:10

質問

前のページに戻るにはどうしたらいいのでしょうか?私は使用しています [react-router-v4][1]

これは、私が最初のランディングページで設定したコードです。

<Router>
  <div>
    <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
    <Route exact path="/" component={Page1}/>
    <Route path="/Page2" component={Page2}/>
    <Route path="/Page3" component={Page3}/>
  </div>
</Router>

後続のページに転送するために、単純に

this.props.history.push('/Page2');

しかし、どうすれば前のページに戻ることができるのでしょうか? 以下のようないくつかのことを試してみましたが、うまくいきません。 1. this.props.history.goBack();

エラーを表示します。

TypeError: nullはオブジェクトではありません (評価 'this.props')

  1. this.context.router.goBack();

エラーを表示します。

TypeError: nullはオブジェクトではありません (評価 'this.context')

  1. this.props.history.push('/');

エラーを表示します。

TypeError: nullはオブジェクトではありません (評価 'this.props')

を投稿する Page1 のコードを以下に掲載します。

import React, {Component} from 'react';
import {Button} from 'react-bootstrap';

class Page1 extends Component {
  constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
  }


  handleNext() {
    this.props.history.push('/page2');
  }

  handleBack() {
    this.props.history.push('/');
  }


  /*
   * Main render method of this class
   */
  render() {
    return (
      <div>
        {/* some component code */}


        <div className="navigationButtonsLeft">
          <Button onClick={this.handleBack} bsStyle="success">&lt; Back</Button>
        </div>
        <div className="navigationButtonsRight">
          <Button onClick={this.handleNext} bsStyle="success">Next &gt;</Button>
        </div>

      </div>
    );
  }


export default Page1;

どのように解決するのですか?

バインディングの問題だと思います。

constructor(props){
   super(props);
   this.goBack = this.goBack.bind(this); // i think you are missing this
}

goBack(){
    this.props.history.goBack();
}

.....

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

コードを投稿する前に想定していた通りです。

constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
    this.handleBack = this.handleBack.bind(this); // you are missing this line
}