【问题标题】:How to display a blog post based on it's ID with React?如何使用 React 根据其 ID 显示博客文章?
【发布时间】:2020-12-14 12:05:16
【问题描述】:

在我的新闻组件中,我有一系列帖子:

const cardInfo = [
      {
        id: 1,
        date: "12/07/2020",
        title: "Machine Learning",
        author: "Alex M.",
        text: "text1"
      },
      {
        id: 2,
        date: "12/07/2020",
        title: "AI",
        author: "Alex E.",
        text: "text2"
      }
   ]

渲染数组的renderCard函数:

renderCard = (card, index) => {
return (
  <Row id={index}>
    <Col sm="10">
      <Card key={index}>
        <CardBody>
          <CardTitle tag="h5" className="mb-2 text-muted">
            {card.title}
          </CardTitle>
          <CardSubtitle tag="h6" className="mb-2 text-muted">
            Written on {card.date} by {card.author}
          </CardSubtitle>
          <CardText className="mb-2 text-muted">
            <ReadMoreReact
              text={card.text}
              readMoreText="Read more."
              min={160}
              ideal={200}
            />
          </CardText>
          <CardSubtitle tag="h6" className="mb-2 text-muted">
            Category: {card.category}
          </CardSubtitle>{" "}
          <Button>Read more.</Button>
        </CardBody>
      </Card>
    </Col>
  </Row>
);
};

显示帖子数组以及按日期排序的最近帖子标题的返回语句:

return (
  <div>
    <CareersHeader />
    <div className="news">
      <h1 className="news__title" id="news-title">
        Blog
      </h1>
      <div className="news__content">
        <div className="item1 news__posts">
          {cardInfo.map(this.renderCard)}
        </div>
        <div className="item2 news__recent_posts">
          <div>Recents Posts:</div>
          <div>
            {cardInfo
              .sort((a, b) => (a.date > b.date ? 1 : -1))
              .map((post, index) => (
                <button onClick={what to do} key={index}>
                  {post.title}
                </button>
              ))}
          </div>
        </div>
      </div>
    </div>
  </div>
);

最近帖子列表中的帖子标题是按钮。当您单击一个按钮时,它应该会打开该特定的博客文章。我在 App.js 中添加了这条路线:

<Route exact path="/news/:id" component={BlogPostDetails} />

BlogPostDetails 组件

return (
  <div>
    <CareersHeader />
    <div className="news">
      <h1 className="news__title" id="news-title">
        Blog
      </h1>
      <div className="news__content">
        <div className="item1 news__posts">
          <p>Blog post</p>
          {cardInfo.map((card) => (
            <div key={card.id}>{renderCard}</div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

但是,我不知道如何将 URL 中的 id 与点击的帖子标题的 id 匹配。 我曾尝试使用 useParams() 钩子,但我遇到了无法解决的错误(无效的钩子调用)。另外,我想知道是否可以创建一个在单击按钮时调用的函数,如下所示:

const displayPost= (index) => {
  const url = "/news/" + index;
  window.open(url, "_top");
};

我确信 React 中有很简单的方法可以做到这一点,只是我还是新手,不了解生命周期。帮助表示赞赏。

【问题讨论】:

  • 您可以尝试使用window.location.pathname 或浏览此示例(reactrouter.com/web/example/url-params) 并确保您没有遗漏任何内容
  • 你使用的是什么 'react-router-dom' 版本,所以你在 useParams 钩子上遇到错误?
  • :) 这正是我尝试实现的。问题是我收到错误消息说我不能在类组件中使用钩子。所以我花了一些时间试图解决它,但无济于事。无论如何,谢谢,将进一步看看。
  • @NemanjaLazarevic 版本是 15.something。我已将其更新到最新版本,但仍然遇到相同的错误。我的节点模块中确实有两次 router-dom,我读到这也可能是问题。
  • 是的,您不能在 class 组件中使用 hooks。既然你有最新版的react-router-dom,能不能在你的&lt; BlogPostDetails /&gt;登录console.log(this.props.match.params)

标签: reactjs react-router react-dom


【解决方案1】:

标题部分。

    import { useHistory } from 'react-router-dom'
    .    
    .
    .
    function MyPage({ ...rest }){
    
    const history = useHistory()

    return(
    .
    .
    .
    {cardInfo
     .sort((a, b) => (a.date > b.date ? 1 : -1))
     .map((post, index) => (
      <button onClick={() => history.push(post.id)} key={index}>
          {post.title}
      </button>
      ))}
    .
    .
    .
    }
    .
    .
    .
)

BlogPostDetails 组件

import { useRouteMatch } from 'react-router-dom'

const DetailPage = ({
...rest
}){

const match = useRouteMatch()
const { id } = match.params

const [ cardInfo, setCardInfo ] = useState([])
const [ loading, setLoading ] = useState(false)
const [ error, setError ] = useState(null)

useEffect(() =>{
   setLoading(true)
   //fetch your details from API and set Loading, Error
}, [ id ])

return ( 
     <div>
        <CareersHeader />
        <div className="news">
           <h1 className="news__title" id="news-title">
               Blog
           </h1>
        <div className="news__content">
        <div className="item1 news__posts">
          <p>Blog post</p>
          {!loading && cardInfo.map((card) => (
            <div key={card.id}>{renderCard}</div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

}




【讨论】:

  • 哦,我想我已经错过了几分钟,现在我知道你正在将你的组件作为类组件。这没有帮助
  • 试试 ComponentDidMount 生命周期。 if(window){ const { location } = window //do something with it}会给你一个url信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 2021-07-11
相关资源
最近更新 更多