1

我正在尝试制作一个组件,列出我最近在 Medium 上的 3 篇文章。我希望它只列出帖子的标题并链接到帖子。

到目前为止,我有MediumItem下面调用的 List Item 组件是我的设置方式:

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

我无法弄清楚如何将 Title 和 URLs 传递给 MediumItem 组件,并确保它只列出最后 3 个项目。

4

1 回答 1

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'
}
于 2019-03-13T21:42:02.173 回答