简体   繁体   English

反应路由器路由 <Link> v5

[英]react-router routes <Link> v5

I am trying to understand nested react routes. 我试图了解嵌套的反应路线。 My current issue is that my link outputs undefined and also renders the component on the same view instead of loading just that component view. 我当前的问题是我的链接输出未定义,并且还将组件呈现在同一视图上,而不是仅加载该组件视图。

Events.js Events.js

const data = {
   "events":[
      {
         "id":"1234",
         "name":"Meetup",
         "description":"Tech meetup"
      },
      {
         "id":"34234",
         "name":"Test",
         "description":"Events"
      }
   ]
}

{data.events.map(event => (
    <Link to={`/events/${data.events.id}`}>
        <EventCard data={event} />
    </Link>
))}

<Switch>
  <Route path={`/events/:eventId`}  render={(props) => <Event {...props}  />}/>
</Switch>

How can I render the Event component when a user has clicked one of the event card. 用户单击事件卡之一时,如何渲染事件组件。 I can currently load both components on the same page but that is not my desired output. 我目前可以在同一页面上加载这两个组件,但这不是我想要的输出。 The expected path should be: 预期路径应为:

Expected: 预期:

Render only 仅渲染

Current: 当前:

Renders & on same page 呈现和在同一页面上

You need to add id param to your event endpoint: 您需要向事件端点添加id参数:

 <Route path="/events/:id?" component={Event} />

Then in the Event you can check if id is present via props.match.params.id . 然后,在Event您可以通过props.match.params.id检查id是否存在。

At first you have got a problem here, 起初,您在这里遇到问题,

<Link to={`/events/${data.events.id}`}>

Since you are already mapping event object from data array, iterator event already holds event data. 由于您已经在映射数据数组中的事件对象,因此迭代器事件已经保存了事件数据。 So you should change it like this; 所以你应该这样改变它;

<Link to={`/events/${event.id}`}>

Also I'd strongly recommend to use 'exact' prop in your routes for routing multiple endpoints from same root like this. 另外,我强烈建议您在路由中使用“精确”属性,以从同一根路由多个端点,如下所示。

<Route exact path={`/events/:eventId`}  render={(props) => <Event {...props}  />}/>

See here for further information. 有关更多信息,请参见此处。 Difference between exact path and path 精确路径与路径之间的差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM