【发布时间】:2016-09-15 13:29:58
【问题描述】:
我正在从 http://jsonplaceholder.typicode.com/users 请求一个示例 JSON 数组,并在 ReactJS 项目中使用该数组的名称值创建一个项目列表。
列表是一个Grommet 列表,我使用.map 函数将Web 服务数据映射到每个列表项。
但是当代码呈现时,而不是使用 Web 服务创建名称列表。它只创建一个列表项并将调用呈现给.map 和rows.push。
问题:
如何在 ReactJS 中将 JSON 数组映射到 List?
这是我尝试过的,首先通过 AJAX GET 获取 Web 服务,然后调用 .map 将该数据映射到列表:
loadNameData() {
$.ajax({
url: 'http://jsonplaceholder.typicode.com/users',
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('#GET Error', status, err.toString());
}.bind(this)
});
}
getInitialState(){
return {
data: {
names: []
}
};
}
componentDidMount() {
this.loadAssetData();
}
render() {
let layerNode;
var rows = [];
layerNode = (
<Layer flush={true} closer={true} onClose={() => this._onCloseLayer()} align='right'>
<Box pad='medium' colorIndex='grey-3'>
<Heading>Filter Options</Heading>
<Label>Names</Label>
this.props.data.names.map(function(name) {
rows.push(<ListItem justify="between">)
rows.push(<span>)
rows.push({name})
rows.push(</span>)
rows.push(</ListItem>)
}
<List selectable={true} selected={0}>
{rows}
</List>
</Box>
</Layer>
);
return (
<Section pad="small" full="vertical" flex={true}>
{layerNode}
</Section>
);
}
【问题讨论】:
-
您了解
.map()的工作原理,对吧?您传递给它的匿名函数不会显式返回任何内容,这意味着每次都会返回undefined。所以你的.map()正在返回一个undefined值的数组。 -
@MichaelParker 我再次查看了 .
map方法,现在我看到我需要将项目传递给映射,然后返回该项目。但是下面给出了我的 return 语句的语法错误。知道为什么吗? hastebin.com/ewebohocom.js -
我认为你不应该在这里返回一个数组。您的逻辑类似于“对于每个名称,呈现一个
<ListItem />”,对吗?所以你应该返回<ListItem />。 -
我发现还有其他 3 个问题,您可能会在修复此问题后遇到。
-
我正在努力解决我所看到的一切问题
标签: javascript json ajax reactjs