从react组件进行REST调用

use*_*mda 28 rest json dom fetch reactjs

我正在尝试从react组件进行REST调用,并将返回的JSON数据呈现到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?
        );
    }
Run Code Online (Sandbox Code Playgroud)

为了在DOM中绑定返回的json?

D. *_*lsh 44

您的代码中存在一些错误.可能绊倒你的那个是this.setState({items:result.json()})

Fetch的.json()方法返回一个promise,因此需要将其作为async处理.

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

我不知道为什么要.json()回报一个承诺(如果有人能说清楚,我很感兴趣).

对于渲染功能,这里你去......

<ul>
   {this.state.items.map(item=><li key={item.id}>{item.body}</li>)}
</ul>
Run Code Online (Sandbox Code Playgroud)

不要忘记独特的钥匙!

对于另一个答案,没有必要绑定地图.

这是工作......

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

  • .json()返回一个promise,因为JSON.parse()在一个大的结果上非常慢,并且因为它失败时会抛出异常. (9认同)
  • @JoachimSchirrmacher我指的是为什么result.json()会返回一个promise.没有任何关于它需要在当前执行上下文之外执行. (4认同)