以下 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/