首页 > 解决方案 > 如何访问“this.props.match.params”以及其他道具?

问题描述

我的父组件中有这段代码:

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

其中 match 属性将是一个从子组件 (ChampionDetails) 检索数据的函数。我的 ChampionDetails (child) 组件的片段:

    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;

这里的问题是,如果我在父母的路线中有 match={},那么 this.props.match.params.id 将变得未定义。如果我删除 match={} 那么我可以检索 this.props.match.params.id

我想知道在我的情况下是否可以在仍然可以访问 this.props.match.params.id 的同时传递其他道具。

任何帮助都感激不尽!

标签: javascriptreactjsreact-router

解决方案


如果您使用的是react-routerversion >=4,您应该能够通过withRouterHOC 访问路由器内部任何组件的路由器参数。例如:

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

推荐阅读