Ash*_*Ash 6 json fetch reactjs
我试图在我的反应应用程序中从api渲染一些关于某个人位置的JSON.
我正在使用isomorphic-fetch从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);
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试解决的是我如何能够在我的组件中获取此响应并将其呈现在当前看起来像这样的组件中(在此示例中,下面的代码数据来自本地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>
)
}
Run Code Online (Sandbox Code Playgroud)
vij*_*yst 16
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 });
});
}
Run Code Online (Sandbox Code Playgroud)
渲染组件应映射状态:
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>
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38769 次 |
| 最近记录: |