gpt4 book ai didi

json - 在react应用程序中使用fetch渲染json数据

转载 作者:行者123 更新时间:2023-12-03 13:28:20 24 4
gpt4 key购买 nike

我正在尝试从我的 React 应用程序中的 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 应该设置状态:

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>
})

关于json - 在react应用程序中使用fetch渲染json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com