【问题标题】:How do I display all comments from an API?如何显示来自 API 的所有评论?
【发布时间】:2021-10-28 18:28:20
【问题描述】:
function News() {
const[stories, setStories] = useState([]);


useEffect(() => {

    const getStoriesData = async () => {
        await fetch("https://hn.algolia.com/api/v1/search_by_date?tags=(story,poll)")
        .then((response) => response.json())
        .then((data) => {

            const stories = data.hits.map(({title,url,points,children}) => ({title,url,points,children}))
            console.log(stories)

            setStories(stories);
        });
    }

    getStoriesData();
}, []);


return(
    <div className="news">
        <table className = "table">
            <tr ><th>Title</th> <th>Points</th></tr>
            {stories.map((story) => (            
                <tr>
                    <td><a className="title" href={story.url}>{story.title}</a></td>
                    <td><div className="points">{story.points}</div></td>
                    <td><div className="comments">{story.children.length}</div></td>
                </tr>               
            ))}
        </table>
    </div>
    
)
}

我必须在给定 API 中显示给定 ID 的所有 cmets(“children”字段)列表,但我不知道如何访问它。评论是树形的。 我尝试了上述方法,但没有奏效。 身份证前:https://hn.algolia.com/api/v1/items/12701272

【问题讨论】:

  • 此端点 https://hn.algolia.com/api/v1/search_by_date?tags=(story,poll) 在响应中没有名为 children 的键。

标签: javascript reactjs json api


【解决方案1】:

如果 cmets 存储在子项中,则需要嵌套的 map 函数。这与您对每个故事所做的概念相似 - 故事上的地图方法以编程方式映射每个单独的故事。现在,您想要的是每个故事中的每个单独的评论。因此,在故事地图功能中还有另一个地图功能,类似于:

stories.map((story) => {
    ...what you had before...
    children.map((comment) => { return <div>comment.text</div> }); 
});

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 2021-10-29
    • 2019-04-12
    • 2019-12-07
    • 2019-07-16
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多