4
votes

Comment accéder à 'this.props.match.params' avec d'autres accessoires?

J'ai ce code dans mon composant parent:

    import React, { Component } from 'react';

    class ChampionDetails extends Component {
      state = {
        champId:this.props.match.params.id,
        champData:null,
        match:false
      }

      componentDidMount(){
        console.log('ChampionDet mounted')
        this.handleChampInfo();
        console.log(this.props.match)
      }

      componentDidUpdate(){
        console.log('ChampionDet updated')
      }


      handleChampInfo=()=>{
        let champData = [];
        let id = this.state.champId
        console.log(id)
        fetch('/api/getChampion?id='+id)
          .then(data=> { return data.json() })
          .then(json=> {
            console.log(json.data);
            champData.push(json.data);
            this.setState({
              champData:json.data,
              match:true
            })
            this.props.match(true)
            // this.props.history.push('/champions/'+id)
          })
          .catch(err=>{
            console.log(err)
          })
      }

      render(){
        return(
          <div>
            <p>{this.state.champId}</p>
            {this.state.champData===null ? null:<p>{this.state.champData.roles}</p>}
          </div>
        )
      }
    }

    export default ChampionDetails;

où l'accessoire de correspondance sera une fonction qui récupère les données du composant enfant (ChampionDetails). Un extrait de mon composant ChampionDetails (enfant):

<Route path='/champions/:id' render={(props) => <ChampionDetails {...props} match={this.handleMatch}/>}/>

Le problème ici est que si j'ai le match = {} dans la route de mon parent, alors this.props.match. params.id deviendra indéfini. Si je supprime match = {} alors je peux récupérer this.props.match.params.id

Je voudrais savoir s'il est possible de passer d'autres accessoires tout en ayant toujours accès à this.props .match.params.id dans mon cas.

Toute aide sera très appréciée!


0 commentaires

3 Réponses :


7
votes

Vous pouvez passer matchProps comme accessoires du routeur, this.props pour tous les accessoires du parent, puis éviter simplement d'écraser les accessoires - votre match prop remplace les accessoires de la route:

<Route path='/champions/:id' render={(matchProps) =>
  <ChampionDetails
    {...matchProps}
    {...this.props}
    handleMatch={this.handleMatch}
  />
}/>

Lorsque vous diffusez {... props} , votre match remplace prop match de react-router .


0 commentaires

0
votes

Match prop fait partie du react-router-dom , donc en créant un autre accessoire appelé match, vous l'écrasez.

Le moyen le plus simple: renommez simplement le match = {this.handleMatch} />} en quelque chose d'autre comme matchHandler={this.handleMatch}/>}

Si l'utilisation du nom match est essentielle, détruit-le comme const {matchHandler: match} = this.props


0 commentaires

12
votes

Si vous utilisez react-router version > = 4 , vous devriez pouvoir accéder aux paramètres du routeur sur n'importe quel composant à l'intérieur du routeur via withRouter HOC. Par exemple:

import { withRouter } from 'react-router-dom';
...
export withRouter(ChampionDetails);


0 commentaires