我正在尝试从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中?
您的代码中有几个错误。可能会使您绊倒的是this.setState({items:result.json()})
this.setState({items:result.json()})
Fetch的.json()方法返回一个Promise,因此将需要作为异步处理。
.json()
fetch(`http://jsonplaceholder.typicode.com/posts`) .then(result=>result.json()) .then(items=>this.setState({items}))
我不知道为什么.json()要兑现诺言(如果有人可以阐明,我很感兴趣)。
对于渲染功能,您可以在这里…
<ul> {this.state.items.map(item=><li key={item.id}>{item.body}</li>)} </ul>
不要忘记唯一的钥匙!
对于其他答案,则无需绑定地图。
它在这里工作…
http://jsfiddle.net/weqm8q5w/6/