如何将道具传递到动态路线?

时间:2019-07-17 06:16:31

标签: reactjs

我创建了一个动态路线列表(发布)和单个路线的组成部分(发布),但是我无法确定将道具传递到每个路线。我简化了代码,只保留了有关路由的内容。

这是“帖子”部分:

import React, { Component } from 'react';
import Post from './Post';
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom';

const shutruk = [
  {
    "id": 1,
    "title": "Shutruk-Nahhunte",
    "info": "Was king of Elam from about 1184 to 1155 BC"
  },
  {
    "id": 2,
    "title": "Shilkhak-Inshushinak",
    "info": "Was king of Elam from about 1150 to 1120 BC"
  },
  {
    "id": 3,
    "title": "Untash-Napirisha",
    "info": "He was the son of the previous Elamite king"
  },
  {
    "id": 4,
    "title": "Kutik-Inshushinak",
    "info": "His father was Shinpi-khish-khuk, the crown prince"
  }
];

class Posts extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
        <Link to="/posts"><h2 className="center" >Posts</h2></Link><br/>
        <div className="center"><img src={require('../img/orn.png')} alt="" className="orn" /></div>     
          <Switch>
            <Route path="/posts" exact component={Home} />
            <Route path="/posts/:id" component={Post} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

const Home = () => (
  <div>
    {
      shutruk.map(shutruk => (
        <h3><Link to={'posts/' + shutruk.id}>{shutruk.title}</Link></h3>
      ))
    }
  </div>
);

export default Posts;

Post组件:

import React, { Component } from 'react';

class Post extends Component {
  render() {
    return (
      <div>
        <h3></h3> //Here should be each value from "title"
        <h5></h5> //Each "info" value   
      </div>
    );
  }
}

export default Post;

如何以正确的方式进行操作? 提前非常感谢!)

2 个答案:

答案 0 :(得分:2)

您只需使用render prop模式并使用相关数据来渲染Post路线

<Route path="/posts/:id" render={(props) => {
   const id = props.match.params.id;
   const data = shutruk.find(item => item.id === id);
   if(data) {
       return <Post {...props} {...data} />
   }
   return <Redirect to="/not-found" />
}}  />

答案 1 :(得分:1)

[已编辑]

注意:当用户单击链接时,通过链接传递数据将正常工作。但这会引起问题,当用户使用url进入页面或仅刷新页面时,则没有数据。然后,您必须检查并在没有数据时提取它。

所以我认为最好像@Shubham Khatri's answer


请检查React Router文档:https://reacttraining.com/react-router/web/api/Link

<Link>接受to属性的对象值, 这样您就可以像这样传递数据:

<Link
  to={{
    pathname: 'posts/' + shutruk.id,
    state: { shutruk: shutruk }
  }}
/>