我有一系列元素,如:
const arr = [
0: {name: aaaa, age:33, color: red}
1: {name: bbbb, age:22, color: blue}
2: {name: cccc, age:55, color: yellow}
当我写一个类似http://localhost/aaaa的路径时,我会这样做,它会渲染一个数组的实际元素,我想在反应路由器上定义它。
有什么建议吗?
答案 0 :(得分:0)
您可以使用具有name
参数的单个路径处理此问题:
<Route path="/:name" component={MyComponent} />
...
componentDidMount() {
const arr = [
{name: aaaa, age:33, color: red},
{name: bbbb, age:22, color: blue},
{name: cccc, age:55, color: yellow}
];
const match = arr.find( item => item.name === this.props.match.params.name );
// Render match
}
答案 1 :(得分:0)
在父元素上看起来像这样
&LT; PropsRoute确切路径=&#39; /:name&#39; component = {PlanetInfo} onePlanet = {singlePlanet} planetList = {planet /&gt;
和子组件
类PlanetInfo扩展了React.Component { componentDidMount(){
const match = this.props.onePlanet.find( item => item.name === this.props.match.params.name );
}
backToPlanetList = () => {
this.props.history.push('/')
}
render(){
console.log(match)//here is undefined
const {onePlanet} = this.props;
return (
<div>
<button onClick={this.backToPlanetList}>Back to the list</button>
<h1>name: {onePlanet.name}</h1>
<p>climate: {onePlanet.climate}</p>
<p>diameter: {onePlanet.diameter}</p>
<p>rotation period: {onePlanet.rotation_period}</p>
</div>
)
}
}