「値」としてインポートされるこのようなjsonからデータをプルしようとしています
{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}
私は.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>
)
})
あなたのデータとコードにはいくつかのエラーがあると思います。しかし、それらを修正し、名前を「person」から「people」に変更した後、それが目的の場合は、次のコードが実行しようとしていることを実行します。
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"));
そして、これがそのためのJSBinです:https://jsbin.com/coyalec/2/edit?html、js、output
更新:より詳細な例で回答を更新しています。'contents'などのエントリが何であるかを想定していないように、データをより一般的に処理するようになりましたが、 'people'や 'pets'などの各タイプは配列であることがわかります。
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"));
そして、これが最新のJSBinです:https://jsbin.com/coyalec/4/edit?html、js、output
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加