Javascript 如何访问“this.props.match.params”以及其他道具?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54114416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:12:03  来源:igfitidea点击:

How to access 'this.props.match.params' along with other props?

javascriptreactjsreact-router

提问by raylism

I have this code in my parent component:

我的父组件中有此代码:

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

where the match prop will be a function that retrieves data from the child component (ChampionDetails). A snippet of my ChampionDetails (child) component:

其中匹配道具将是一个从子组件(ChampionDetails)中检索数据的函数。我的 ChampionDetails(子)组件的片段:

    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;

The problem here is that if I have the match={} in my parent's route, then this.props.match.params.id will become undefined. If I remove match={} then I can retrieve this.props.match.params.id

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

I would like to know if its possible to be able to pass other props while still have access to this.props.match.params.id in my case.

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

Any help will be much appreciated!

任何帮助都感激不尽!

回答by Toby

You can pass matchPropsas the props from the router, this.propsfor any props from the parent and then just avoid overwriting props - your matchprop is overriding the props from the route:

您可以matchProps作为来自路由器的道具传递,this.props对于来自父级的任何道具,然后避免覆盖道具 - 您的match道具正在覆盖路线中的道具:

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

When you spread {...props}your matchprop overrides react-router's match.

当你传播{...props}你的match道具时,会覆盖 react-router 的match.

回答by Rafael Sousa

If you're using react-routerversion >=4, you should be able to access the router params at any component inside the router via withRouterHOC. For instance:

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

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

回答by Amir-Mousavi

Match prop is part of the react-router-dom, so by making another props called match you are overwriting it.

Match 道具是 的一部分react-router-dom,因此通过制作另一个名为 match 的道具,您将覆盖它。

The simplest way: just rename the match={this.handleMatch}/>}to something else like matchHandler={this.handleMatch}/>}

最简单的方法:只需将 重命名match={this.handleMatch}/>}为其他类似的东西 matchHandler={this.handleMatch}/>}

If using the name matchis essential, destruct it as const {matchHandler : match} = this.props

如果必须使用名称match,请将其销毁为const {matchHandler : match} = this.props