【发布时间】:2017-09-25 09:45:39
【问题描述】:
我对开始使用 reactjs 的结果有点失望。
我现在只是试图从一个简单的 restful ws 中解析 json 数据。
如果我把rest get查询的url放在chrome上,它会正确回答一个json数组:
[{"label":"TestLabel!!","value":7,"rating":17.25},{"label":"TestLabel2 !!","value":8,"rating":18.25}]
这是我的 React 组件:
export default class ItemLister extends React.Component {
constructor() {
super();
this.state = { items: [{"label":"Test1!!","value":7,"rating":17.25}] };
}
componentDidMount() {
fetch('/rest/json/product/get')
.then(result=> {
this.state.items.push(result);
});
}
render() {
return(
<div>
<div>Items:</div>
{
this.state.items.map(function(item, i){
return <div key={i}>{item.label}</div>
}
)}
</div>
);
}
}
经过大量调整后,没有显示任何错误,但列表没有任何反应,仅显示构造函数元素。
请指点我正确的方向...
谢谢
已解决:
建议的“setState()”是问题的一部分。 另一部分是我管理 json 答案的方式。
这个项目是这样运作的:
componentDidMount() {
fetch('/rest/json/product/get')
.then(response => response.json())
.then(response => {
this.setState({items: response });
})
}
但我只是偶然尝试了另一种方法来实现调用,因为我完全迷路了。 我觉得有点困惑。实现提取的正确方法是什么?
不管怎样……没关系。
【问题讨论】:
-
检查响应是否具有正确的内容类型,我希望如果未指定,您将获得 text/plain 而不是 javascript/application 或其他任何当前约定
-
你试过
this.setState而不是this.state.items.push(result);吗?另外我不认为在componentDidMount这样做是个好主意 -
您正在尝试将数组作为另一个对象推送到数组...
-
试试
this.setState('items',result) -
这样我得到了'Uncaught (in promise) TypeError: this.state.items.map is not a function'。 json有问题吗?但输出是一个正确的 json 数组。