为阵列的每个元素反应路由器唯一路径

问题描述 投票:0回答:2

我有一系列元素,如:

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这样的路径时,我会这样做,它会渲染一个数组的实际元素,我想在反应路由器上定义它。

有什么建议?

arrays reactjs path react-router
2个回答
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
}

0
投票

在父元素上看起来像这样

<PropsRoute exact path ='/:name'component = {PlanetInfo} onePlanet = {singlePlanet} planetList = {planet />

和儿童组成部分

class 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>
    )
}

}

© www.soinside.com 2019 - 2024. All rights reserved.