[英]Component is not Getting Rendered - Dynamic Routing React
I can get the data of the players when i Route to the Players Component, but when i click on the Link Tags, the PLayersContainer Component is not opening.当我路由到播放器组件时,我可以获得播放器的数据,但是当我单击链接标签时,播放器容器组件没有打开。 This is my App.js File.
这是我的 App.js 文件。
import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import Players from './Components/Players'
import PlayersContainer from './Components/Container/playersContainer'
import Navigation from './Components/Navigation';
export default class App extends Component {
state = {
players:[
{
id:1,
name:'Ronaldo'
},
{
id:2,
name:'Messi'
}
]
}
render() {
return (
<Router>
<Navigation />
<Switch>
<Route path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route exact path="/players/:id" render={PlayersContainer} />
</Switch>
</Router>
)
}
}
This is my Players Component.这是我的玩家组件。
import React from 'react'
import { Link } from 'react-router-dom'
export default function Players(props) {
const renderPlayers = () => {
let players = props.players.map(playerObj => <li> <Link to={`/players/${playerObj.id}`}> Player {playerObj.name} </Link></li>)
return players
}
return (
<div>
<ul>
{renderPlayers()}
</ul>
</div>
)
}
This is my PlayersContainer Component, where i want to render the individual data of the Player.这是我的 PlayersContainer 组件,我想在其中呈现 Player 的各个数据。
import React from 'react'
import { Link } from 'react-router-dom'
export default function PlayersContainer(props) {
const renderPlayers = () => {
console.log(props);
}
return (
<div>
<ul>
{renderPlayers()}
</ul>
</div>
)
}
You have the wrong Route
marked as exact
.您将错误的
Route
标记为exact
。 The way its written currently, anything beginning with /players
will match the first route.按照目前的编写方式,以
/players
开头的任何内容都将匹配第一条路线。 Since its in a switch, only the first match will be rendered.由于它在开关中,因此只会渲染第一个匹配项。
Change it from:将其更改为:
<Route path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route exact path="/players/:id" render={PlayersContainer} />
to this:对此:
<Route exact path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route path="/players/:id" render={PlayersContainer} />
Now only exactly /players
will match the first route, and /players/id
can continue past it to match the second.现在只有
/players
会匹配第一个路由,而/players/id
可以继续通过它匹配第二个路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.