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

时间:2018-01-08 08:55:55

标签: javascript reactjs dictionary fetch

以下反应应用程序应在单击按钮时从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不是函数'错误,因为this.state.items是一个promise而不是调用render时的列表。

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

2 个答案:

答案 0 :(得分:0)

尝试

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以获取良好示例。

答案 1 :(得分:0)

你最初不应该使用map,在使用循环之前给出任何条件或者映射你的变量中是否有数据可用,如果只是循环,那么就做一些默认的事情。

示例我已经给过一次检查:

render(){
            return(
                <div>
                    <button onClick={(event)=>this.fetchHotels(event)}>Hotel list</button>
                    <ul>
                       {(this.state.items)?this.state.items.map(function(item){
                           return(
                            <li></li>
                           )
                           }):null}
                    </ul>
                </div>
            )
        }
相关问题