我正在尝试制作一个列出我最近在Medium上发表的3篇文章的组件。我希望它只列出帖子的标题并链接到该帖子。
到目前为止,我具有以下设置的名为MediumItem
的列表项组件:
import React from 'react'
import { ExternalLink } from "react-feather"
const MediumItem = (props) => (
<li><a href={props.url}>{props.title} <ExternalLink/></a></li>
)
export default MediumItem
我的供稿设置如下:
import React from 'react'
import axios from 'axios'
import MediumItem from './mediumItem'
import { ExternalLink } from "react-feather"
class Medium extends React.Component {
state = {
posts: []
}
componentDidMount() {
this.fetchPosts().then(this.setPosts)
}
fetchPosts = () => axios.get(`https://cors-anywhere.herokuapp.com/https://us-central1-ryan-b-designs-medium-cors.cloudfunctions.net/medium?username=@RyanABrooks`)
setPosts = ({data}) => {
const { Post } = data.payload.references
const posts = Object.values(Post).map(({ id, title, uniqueSlug}) => Object.assign({}, {
title,
url: `https://medium.com/@RyanABrooks/${uniqueSlug}`
}))
this.setState({
posts
})
}
render() {
return (
<div>
<h3>Recent Articles</h3>
<ul>
{ this.state.posts.map(({posts}, i) =>
<MediumItem key={i} {...posts} />
)}
<li><a href="https://medium.com/@RyanABrooks">Read More <ExternalLink /></a></li>
</ul>
</div>
)
}
}
export default Medium
我在弄清楚如何将标题和URL传递给MediumItem组件时遇到麻烦,并确保仅列出最后3个项目。
答案 0 :(得分:2)
可能是这样的:
render() {
const last3 = this.state.posts.slice(-3);
{ last3.map((post, i) => // no need to use {posts} here
<MediumItem key={i} title={post.title} url={post.url} />
)}
}
假设每个帖子的结构为:
{
title: 'asdf',
url: 'https://asdf'
}