2017-07-12 4 views
1

私は、自分の反応コンポーネントクラスにMatchオブジェクトを渡すことで、私のURLをパラメータとして使用しようとしています。しかし、それは動作していません!私はここで間違って何をしていますか?ReactJsコンポーネントクラスにMatchオブジェクトを含めるにはどうすればいいですか?

コンポーネントをJavaScript関数として作成すると、すべて正常に動作しますが、コンポーネントをJavaScriptクラスとして作成しようとすると機能しません。

おそらく私は何か間違っていますか? Matchオブジェクトをクラスコンポーネントに渡して、それを使用してコンポーネントの状態を設定するにはどうすればよいですか?

マイコード:

import React, { Component } from 'react'; 

import axios from 'axios'; 

import PropTypes from 'prop-types'; 

class InstructorProfile extends Component { 

    constructor(props, {match}) { 

    super(props, {match}); 

    this.state = { 
     instructors: [], 
     instructorID : match.params.instructorID 
    }; 

    } 

    componentDidMount(){ 


     axios.get(`/instructors`) 
     .then(response => { 
     this.setState({ 
      instructors: response.data 
     }); 
     }) 
     .catch(error => { 
     console.log('Error fetching and parsing data', error); 
     }); 
    } 

    render(){ 
    return (
     <div className="instructor-grid"> 

     <div className="instructor-wrapper"> 

     hi 

     </div> 

     </div> 
    ); 
    } 
} 

export default InstructorProfile; 

答えて

2

リアクタ - ルータのRouteコンポーネントパスmatchオブジェクトは、デフォルトでラップするコンポーネントに対して、小道具を介して送信されます。以下に、あなたのconstructor方法を交換してみてください:

constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     instructors: [], 
 
     instructorID : props.match.params.instructorID 
 
    }; 
 
}

は、この情報がお役に立てば幸いです。

+0

これは完全にあなたにとても感謝しました! – vanegeek

1

あなたのコンストラクタ唯一のあなたは小道具がint型を経由してそのマッチオブジェクトを渡す必要が

constructor(props) { 
    super(props); 
    let match = props.match;//← here 

    this.state = { 
    instructors: [], 
    instructorID : match.params.instructorID 
    }; 
} 

...小道具は、あなたがそれでmatchを配置する必要があり、オブジェクトを受け取ります親コンポーネント:

// in parent component... 
render(){ 
    let match = ...;//however you get your match object upper in the hierarchy 
    return <InstructorProfile match={match} /*and any other thing you need to pass it*/ />; 
} 
+0

これは素晴らしい感謝です! – vanegeek

関連する問題