【问题标题】:Set Up Medium Feed in React在 React 中设置 Medium Feed
【发布时间】:2019-03-14 05:55:45
【问题描述】:

我正在尝试制作一个组件,列出我最近在 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

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

【问题讨论】:

标签: reactjs ecmascript-6 gatsby medium.com


【解决方案1】:

可能是这样的:

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'
}

【讨论】:

  • 这个没问题。但我觉得最好明确地说出你传递了哪些道具,而不是从 api 传播数据。只是为了可读性。
  • 也许,但似乎 OP 想要使用 {...post} - 无论如何都改变了
  • 是的,该解决方案在大多数情况下都可以正常工作。我只是说,就可读性而言,最好明确说明发生了什么。特别是当没有像 typescript、flow 或 propTypes 这样的类型提示时。 (个人意见)
猜你喜欢
  • 1970-01-01
  • 2016-08-23
  • 2020-08-05
  • 2012-05-18
  • 1970-01-01
  • 2017-07-29
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多