私はreactアプリのAPIから人の場所に関するJSONをレンダリングしようとしています。
私は同形フェッチを使用してAPIからデータにアクセスしています。基本テストを追加すると、以下を使用してデータが正しくログに記録されます。
require('isomorphic-fetch');
require('es6-promise').polyfill();
var url = 'http://localhost:3000/api/data'
fetch(url)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
console.log(data);
});
私が解決しようとしているのは、この応答を取得して、現在このようになっているコンポーネントでレンダリングする方法です(この例では、以下のコードはローカルのjsonファイルから取得されているため、それらをマージする必要があります)。
componentDidMountをセットアップしようとしましたが、構文に頭を悩ませることができたので、壊れ続けました。reduxアクションもチェックしましたが、脳が爆発しました。
const personLoc = Object.keys(data.person.loc).map((content, idx) => {
const items = data.person.loc[content].map((item, i) => (
<p key={i}>{item.text}</p>
))
return <div key={idx}>{items}</div>
})
export default function PersonLocation() {
return (
<div className="bio__location">
{personLoc}
</div>
)
}
componentDidMountはsetStateである必要があります:
componentDidMount() {
var that = this;
var url = 'http://localhost:3000/api/data'
fetch(url)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
that.setState({ person: data.person });
});
}
レンダーコンポーネントは状態をマップする必要があります。
const personLoc = Object.keys(this.state.person.loc).map((content, idx) => {
const items = this.state.person.loc[content].map((item, i) => (
<p key={i}>{item.text}</p>
))
return <div key={idx}>{items}</div>
})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加