javascript - 如何访问“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 的同时传递其他道具。
任何帮助都感激不尽!
解决方案
如果您使用的是react-router
version >=4
,您应该能够通过withRouter
HOC 访问路由器内部任何组件的路由器参数。例如:
import { withRouter } from 'react-router-dom';
...
export withRouter(ChampionDetails);
推荐阅读
- css - 用网格显示等宽元素
- node.js - Express/Node.js 后端点显示 [object Object] 而不是 Array of Objects
- numpy - 如何计算python中三个数组中有多少元素等于数组之间相同位置的某个值?
- pandas - pandas to_datetime 留下未转换的数据
- vega-lite - 鼠标悬停时如何仅在特定轴上缩放?
- python - Pandas 数据框:基于共享相同字符串条目的不同列的色调频率图
- hive - 使用 udf 创建 Hive 表
- python - 如何使用python3替换文本文件中的特定文本
- postgresql - 创建函数时有什么方法可以使 Postgres 更严格?
- python - HotJar 可疑的 UserAgent 错误,谷歌上没有,试图运行 python 刮板工具来跟踪体育赔率