javascript - 从 Reddit/REST API 获取和渲染数据

标签 javascript api ecmascript-6 fetch-api reddit

免责声明:我是一名设计师,正在尝试学习更多 JavaScript。对我宽容一些。

我正在创建一个网站,该网站从 reddit api 获取和呈现帖子,并以 CSS 网格/报纸样式布局显示数据。类似于边缘。到目前为止,这是我的代码:

const url = "https://www.reddit.com/r/upliftingnews.json?raw_json=1&limit=10"

fetch(url)
    .then(res => res.json())
    .then(res => res.data.children)
    .then(res => res.map(post => ({
        author: post.data.author,
        link: post.data.url,
        img: (typeof (post.data.preview) !== 'undefined') ? post.data.preview.images[0].source.url : null,
        // img: post.data.thumbnail,
        title: post.data.title
    })))
    .then(res => res.map(render))
    .then(res => console.log(res))

// fetch(url)
//     .then(response => response.json())
//     .then(response => {
//         console.log(response.data.children[1].data.preview.images[0].resolutions[1].url);
//     });


const app = document.querySelector('#app');

const render = post => {
    //console.log(post.data);
    const node = document.createElement('div');
    node.innerHTML = `
    <h2>
      <a href="${post.link}">
        <img src="${post.img}" />
        ${post.title}
      </a>
    </h2>`;
    app.appendChild(node);
}

所以这工作正常,但是我应该有更有效/性能更好的方法吗?我的问题是:

  1. 我实际上无法控制各个呈现帖子的标记。我可以使用 CSS 和 nth-child 单独设置帖子样式,但这似乎效率低下。
  2. 看起来性能不太好。页面加载后 1 或 2 秒内呈现 html,导致黑屏闪烁。

谷歌搜索与 fetch api/rendering json 有关的任何内容都会显示与react/vue/angular/insertJSLibraryHere相关的结果。

我真的应该使用这些框架之一吗?如果我刚学会如何使用 React 来实现这一点,会不会更容易/更有效?我一直在避免学习 React/Vue,因为我发现它很难理解,但也许这是一个很好的起点?

当每个搜索结果都与某个 JS 框架相关时,很难找到这个问题的答案。这就是为什么我在这里问。

最佳答案

React 中的基本获取示例。

更好的做法是通过 componentWillMount 生命周期方法将 api 调用的响应保存在状态数组中。我也想使用axios而不是获取。

这是一个例子:

import axios from 'axios';

class someComponent extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            redditItems: [];
        }
    }

    componentWillMount = () => {
        axios.get(API_URL).then(res => {
            this.setState({ redditItems: res.data.data.children });
        }).catch(err => {
            // CODE WHEN FAILS.
        });
    }

    renderList = () => {
        return this.state.reditItems.map((item, i) => (
            <div key={ i }>
                <p>{ item.data.url }</p>
                <p>{ item.data.author }</p>
            </div> // HOW YOU WANT TO DISPLAY YOUR ITEM
        ));
    }

    render = () => {
        return (
            <div>
                { this.renderList() }
            </div>
        )
    }
}

希望对你有帮助。

关于javascript - 从 Reddit/REST API 获取和渲染数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309198/

相关文章:

javascript - 出现类型错误,提示我的 websocket 变量未定义

api - 我的网站的 Google 自动完成 api

php - Amazon S3 在创建对象时抛出 cURL 错误

node.js - ServiceWorker 和推送通知负载

javascript - 如何对具有偏移量的数组使用解构

javascript - 无法在 ReactJS 中重复使用复选框功能

javascript - 重新图表 - 在左侧对齐轴标签

javascript - 多个参数与选项对象

javascript - JS try/catch 生成 jshint 错误

json - 如何在 Swift 中将给定的字典转换为包含 JSON 数组的 JSON 对象?