使用react获取json对象数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38886131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting json object data with react
提问by Ash
I am attempting to pull data out of json like this, which is imported as "values"
我试图从这样的 json 中提取数据,该数据作为“值”导入
{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}
I am using .maplike below but getting the error .default.map is not a functionI believe it is because i have objects not arrays, i've tried a bunch of stuff including object.keysbut i'm getting errors all over the place, any direction would be appreciated.
我使用.map如下,但得到错误.default.map is not a function我相信这是因为我有对象而不是数组,我已经尝试了很多东西,包括object.keys但我到处都是错误,任何方向都会受到赞赏。
import values from './sample.json'
const vals = values.map((myval, index) => {
const items = person.items.map((item, i) => {
return (
<div>{item.name}</div>
)
})
return (
<div>{items}</div>
)
})
回答by KumarM
I think your data and code have some errors. But after fixing those and also changing the name from 'person' to 'people' if that's what you are after, here's the code that does what you are trying to do:
我认为您的数据和代码有一些错误。但是在修复这些并将名称从“人”更改为“人”之后,如果这就是您所追求的,这里是执行您要执行的操作的代码:
var data = {
content: {
people: [
{
name: "Test",
age : 24
},
{
name: "Foo",
age: 25
}
]
}
};
var App = React.createClass({
render: function() {
var people = data.content.people.map(function(person){
return (<div>{person.name}</div>);
});
return (<div>{people}</div>)
}
});
ReactDOM.render(<App/>, document.getElementById("app"));
And here's the JSBin for that: https://jsbin.com/coyalec/2/edit?html,js,output
这是 JSBin:https://jsbin.com/coyalec/2/edit?html,js,output
Update:I'm updating the answer with more detailed example. It now deals with data more generically, like it doesn't assume what are the entries of 'contents' and such, but it knows that each type like 'people' or 'pets' are an array.
更新:我正在用更详细的例子更新答案。它现在更通用地处理数据,就像它不假设“内容”的条目是什么等等,但它知道像“人”或“宠物”这样的每种类型都是一个数组。
var data = {
content: {
people: [
{
name: "Test",
age : 24
},
{
name: "Foo",
age: 25
}
],
pets: [
{
name: "Sweety",
age: 3
},
{
name: "Kitty",
age: 5
}
]
}
};
var App = React.createClass({
render: function() {
//Get the keys in data.content. This will return ['people', 'pets']
var contentKeys = Object.keys(data.content);
//Now start iterating through these keys and use those keys to
//retrieve the underlying arrays and then extract the name field
var allNames = contentKeys.map((t) =>
data.content[t].map((e) => (<div>{e.name}</div>))
);
return (<div>{allNames}</div>)
}
});
ReactDOM.render(<App/>, document.getElementById("app"));
And here's the latest JSBin: https://jsbin.com/coyalec/4/edit?html,js,output
这是最新的 JSBin:https://jsbin.com/coyalec/4/edit ?html,js,output

