javascript - 如何在 javascript 中迭代 'fetch' 返回的结果?

标签 javascript reactjs dictionary fetch

以下 React 应用程序应在单击按钮时从 RESTful API 获取数据并将数据表示为 ul:

import React from 'react';
import ReactDOM from 'react-dom';

class RestSample extends React.Component{ 

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

    fetchHotels(event){
        fetch('http://localhost:8000/ui/rest/hotel') 
            .then(data => {
                this.setState({items:data.json()});
            });
    }

    render(){
        return(
            <div>
                <button onClick={(event)=>this.fetchHotels(event)}>Hotel list</button>
                <ul>
                   {this.state.items.map(function(item){
                       return(
                        <li></li>
                       )
                       })}
                </ul>
            </div>
        )
    }
}

ReactDOM.render(
  <RestSample />,
  document.getElementById('root')
);

但是,单击时我收到“this.state.items.map 不是函数”错误,因为调用 render 时 this.state.items 是一个 promise ,而不是一个列表。

我必须在哪里放置代码来迭代 this.state.items 以确保一旦 Promise 返回列表就调用它?

最佳答案

尝试

fetchHotels(event){
        fetch('http://localhost:8000/ui/rest/hotel')
            .then(response => response.json())
            .then(json=> {
                this.setState({items:json.data.map(child => child)});
            });
    }

请参阅https://redux.js.org/docs/advanced/AsyncActions.html举个很好的例子。

关于javascript - 如何在 javascript 中迭代 'fetch' 返回的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146898/

相关文章:

javascript - Owlcarousel2 "dots:true"不工作?

javascript - 我该如何处理这个 800kb 的 JavaScript 文件?

reactjs - render() 中的 connect() ?

c# - 列表字典 (C#)

javascript - Mixpanel 事件会追溯更新吗?

javascript - 使用可选输入设置 ActiveX 属性

javascript - 在 React 中添加/删除类的正确方法

android - 电视 Remote 空间导航

Java map 内容对比

python - 包含字典的类属性