从React组件进行REST调用 [英] Making REST calls from a react component

查看:618
本文介绍了从React组件进行REST调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从react组件进行REST调用,并将返回的JSON数据呈现到DOM中

I am trying to make REST call from a react component and render the returned JSON data into the DOM

这是我的组成部分

import React from 'react';

export default class ItemLister extends React.Component {
    constructor() {
        super();
        this.state = { items: [] };
    }

    componentDidMount() {
        fetch(`http://api/call`) 
            .then(result=> {
                this.setState({items:result.json()});
            });
    }

    render() {        
        return(
           WHAT SHOULD THIS RETURN?
        );
    }

为了将返回的json绑定到DOM中?

In order to bind the returned json in a DOM?

推荐答案

您的代码中有几个错误. this.setState({items:result.json()})

There are a couple of errors in your code. The one that's probably tripping you up is the this.setState({items:result.json()})

Fetch的.json()方法返回一个Promise,因此需要作为异步处理.

Fetch's .json() method returns a promise, so it will need to be dealt with as async.

fetch(`http://jsonplaceholder.typicode.com/posts`)
.then(result=>result.json())
.then(items=>this.setState({items}))

我不知道为什么.json()会返回承诺(如果有人可以阐明,我很感兴趣).

I don't know why .json() returns a promise (if anyone can shed light, I'm interested).

对于渲染功能,在这里...

For the render function, here you go...

<ul>
   {this.state.items.map(item=><li key={item.id}>{item.body}</li>)}
</ul>

别忘了唯一的密钥!

对于其他答案,无需绑定地图.

For the other answer, there's no need to bind map.

它在这里工作...

http://jsfiddle.net/weqm8q5w/6/

这篇关于从React组件进行REST调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆