我正在尝试从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中?
发布于 2016-05-27 19:45:06
您的代码中有几个错误。可能让你被绊倒的是this.setState({items:result.json()})
Fetch的.json()
方法返回一个promise,因此需要将其作为异步处理。
fetch(`http://jsonplaceholder.typicode.com/posts`)
.then(result=>result.json())
.then(items=>this.setState({items}))
我不知道为什么.json()
会返回一个promise (如果有人能解释清楚的话,我很感兴趣)。
对于render函数,请执行以下操作...
<ul>
{this.state.items.map(item=><li key={item.id}>{item.body}</li>)}
</ul>
别忘了唯一的密钥!
对于另一个答案,不需要绑定map。
在这里它起作用了..。
发布于 2016-05-27 14:55:36
您可以尝试对render方法执行以下操作:
render() {
var resultNodes = this.state.items.map(function(result, index) {
return (
<div>result<div/>
);
}.bind(this));
return (
<div>
{resultNodes}
</div>
);
}
别忘了在你的fetch(...).then()
中使用.bind(this)
,我认为没有...它是不能工作的。
发布于 2019-02-25 07:35:45
请改用以下代码。它将工作:(您也可以检查数据,如果加载到控制台中)
constructor(props) {
super(props);
this.state = {
items: []
}
}
componentDidMount() {
fetch('http://api/call')
.then(Response => Response.json())
.then(res => {
console.log(res);
this.setState({
items: res,
});
})
.catch(error => {
console.log(error)
})
}
然后根据需要使用渲染过程中存储在状态中的结果进行显示。
https://stackoverflow.com/questions/37486251
复制相似问题