如何迭代';返回的结果;获取';用javascript?

如何迭代';返回的结果;获取';用javascript?,javascript,reactjs,dictionary,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: [] }; } fetc

单击按钮时,以下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')
);
从“React”导入React;
从“react dom”导入react dom;
类RestSample扩展了React.Component{
建造师(道具){
超级(道具);
this.state={items:[]};
}
酒店(活动){
取('http://localhost:8000/ui/rest/hotel') 
。然后(数据=>{
this.setState({items:data.json()});
});
}
render(){
返回(
this.fetchHotels(event)}>酒店列表
    {this.state.items.map(函数(项)){ 返回(
  • ) })}
) } } ReactDOM.render( , document.getElementById('root')) );
但是,单击会出现“this.state.items.map不是函数”错误,因为调用render时,this.state.items是承诺而不是列表

我必须在何处放置代码来迭代this.state.items,以确保一旦承诺返回列表中的值,就可以调用它?

试试看

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

请参阅示例。

最初不应使用map,在使用loop或map之前,请给出任何条件,以确定变量中是否有可用的数据,如果只有loop,请执行一些默认操作

我曾经举过一个例子:

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>
            )
        }
render(){
返回(
this.fetchHotels(event)}>酒店列表
    {(this.state.items)?this.state.items.map(函数(项)){ 返回(
  • ) }):null}
) }
这就成功了。该方法实际上现在看起来是这样的:fetchHotels(event){fetch(')。然后(response=>response.json())。然后(json=>{this.setState({hotels:json.map(child=>child)});}