Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从Reddit/REST API获取和呈现数据_Javascript_Api_Ecmascript 6_Fetch Api_Reddit - Fatal编程技术网

Javascript 从Reddit/REST API获取和呈现数据

Javascript 从Reddit/REST API获取和呈现数据,javascript,api,ecmascript-6,fetch-api,reddit,Javascript,Api,Ecmascript 6,Fetch Api,Reddit,免责声明:我是一名试图学习更多javascript的设计师。对我宽容点 我正在创建一个网站,从RedditAPI获取和呈现帖子,并以CSS网格/报纸样式的布局显示数据。类似于边缘。以下是我目前的代码: const url = "https://www.reddit.com/r/upliftingnews.json?raw_json=1&limit=10" fetch(url) .then(res => res.json()) .then(res => res

免责声明:我是一名试图学习更多javascript的设计师。对我宽容点

我正在创建一个网站,从RedditAPI获取和呈现帖子,并以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);
}
consturl=”https://www.reddit.com/r/upliftingnews.json?raw_json=1&limit=10"
获取(url)
.then(res=>res.json())
.然后(res=>res.data.children)
.然后(res=>res.map)(post=>({
作者:post.data.author,
链接:post.data.url,
img:(typeof(post.data.preview)!='undefined')?post.data.preview.images[0]。source.url:null,
//img:post.data.缩略图,
标题:post.data.title
})))
。然后(res=>res.map(渲染))
.then(res=>console.log(res))
//获取(url)
//.then(response=>response.json())
//。然后(响应=>{
//console.log(response.data.children[1]。data.preview.images[0]。分辨率[1]。url);
//     });
const app=document.querySelector(“#app”);
const render=post=>{
//控制台日志(post.data);
const node=document.createElement('div');
node.innerHTML=`
`;
app.appendChild(节点);
}
所以这很好,但是有没有一种更有效/性能更好的方法?我的问题是:

  • 我实际上无法控制单个呈现帖子的标记。我可以使用CSS和nth-child分别设置帖子的样式,但这似乎效率低下
  • 这似乎不是很有效。html在页面加载后1或2秒钟内呈现,导致屏幕出现空白闪烁 谷歌搜索与fetch api的/rendering json有关的任何内容都会在此处显示与react/vue/angular/insertJSLibraryHere相关的结果

    我应该实际使用这些框架中的一个吗?如果我刚刚学会如何使用React进行此操作,会更容易/更有效吗?我一直在避免学习React/Vue,因为我觉得很难集中注意力,但也许这是一个好的开始


    当每个搜索结果都与某个JS框架相关时,很难找到答案。所以我在这里问

    反应中的基本提取示例。

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

    以下是一个例子:

    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>
            )
        }
    }
    
    从“axios”导入axios;
    类someComponent扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    redditItems:[];
    }
    }
    组件将装入=()=>{
    get(API_URL).then(res=>{
    this.setState({redditItems:res.data.data.children});
    }).catch(错误=>{
    //失败时编码。
    });
    }
    renderList=()=>{
    返回此.state.reditItems.map((项,i)=>(
    {item.data.url}

    {item.data.author}

    //您希望如何显示您的项目 )); } 渲染=()=>{ 返回( {this.renderList()} ) } }

    我希望它能对您有所帮助。

    谢谢,但我没有使用React。我的问题是,我是否更适合使用诸如React之类的东西来处理这个问题,或者当我可以用vanilla JS来处理所有这些问题时,这样做是没有必要的。很抱歉,误解了。您完全可以像使用fetchapi那样执行此操作。我建议你阅读(如果你还没有读过的话)。对于遇到的性能问题,最好在api调用之前呈现占位符数据。因此,当它被加载时,它将被替换为您的真实数据。毕竟,我认为开始学习Vue或React之类的框架并不是一个坏主意。你会惊讶于与之共事的乐趣。谢谢你的回复!我认为您编辑了您的评论,但我已将fetch改为async/await。当我有时间的时候,我会好好调查一下。