从 React 组件进行 REST 调用

Making REST calls from a react component

我正在尝试从 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?
        );
    }

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

你可以试试你的渲染方法:

render() {
    var resultNodes = this.state.items.map(function(result, index) {
        return (
            <div>result<div/>
        );
    }.bind(this));
    return (
        <div>
            {resultNodes}
        </div>
    );
}

并且不要忘记为您的 fetch(...).then() 使用 .bind(this),我不认为没有...

您的代码中有几个错误。可能让您感到困惑的是 this.setState({items:result.json()})

Fetch 的 .json() 方法 returns 一个承诺,因此需要将其作为异步处理。

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

我不知道为什么 .json() returns 承诺(如果有人能阐明,我很感兴趣)。

对于渲染函数,给你...

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

不要忘记唯一键!

对于其他答案,不需要绑定地图。

正在运行...

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

Fetch 方法将 return 一个 Promise,使编写以异步方式工作的代码变得简单:

你的情况:

componentDidMount(){
  fetch('http://api/call')      // returns a promise object
    .then( result => result.json()) // still returns a promise object, U need to chain it again
    .then( items => this.setState({items}));
}

result.json() return 是一个承诺,因为它适用于 响应流 我们需要先处理整个响应才能工作。

改为使用以下内容。它会工作: (也可以在控制台查看数据)


 constructor(props) {
        super(props);
        this.state = {
            items: []
        }
    }

 componentDidMount() {
        fetch('http://api/call')
            .then(Response => Response.json())
            .then(res => {
                console.log(res);
                this.setState({
                    items: res,
                });
            })
            .catch(error => {
                console.log(error)
            })
    }

然后使用render时state中保存的结果按需显示。