使用fetch在react app中呈现json数据
发布时间:2020-12-15 20:43:30 所属栏目:百科 来源:网络整理
导读:我试图在我的反应应用程序中从api渲染一些关于某个人位置的 JSON. 我正在使用isomorphic-fetch从API访问数据我可以添加基本测试并使用下面正确记录数据. require('isomorphic-fetch'); require('es6-promise').polyfill(); var url = 'http://localhost:3000
我试图在我的反应应用程序中从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); }); 我正在尝试解决的是我如何能够在我的组件中获取此响应并将其呈现在当前看起来像这样的组件中(在此示例中,下面的代码数据来自本地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> }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |