gpt4 book ai didi

javascript - 从API访问数据并在react中输出

转载 作者:行者123 更新时间:2023-11-28 17:49:15 24 4
gpt4 key购买 nike

我有一个 API (/js/feed/sms.json),它返回如下所示的数据:

[
{
id: 1,
name: "Test feeds 1",
headline: "Here is a headline",
feed-url: "/something?q=1"
},
{
id: 2,
name: "Test feeds 2",
headline: "Here is another headline",
feed-url: "/something?q=2"
},
{
id: 3,
name: "Test feeds 3",
headline: "Here is a third headline",
feed-url: "/something?q=3"
}
]

我有几个 React 组件。

第一个是对 API 的调用:fetch-api-data.jsx:

import * as axios from 'axios';

export default class FetchApiData {
constructor() {
console.log('FetchAPIData loaded');
}
static shareMyStoryData(URL) {
return axios.get(URL)
.then(function (response) {

})
.catch(function (error) {
console.log(error);
});
}
}

第二个是解析数据的组件。

import * as React from 'react';
import * as DOM from 'react-dom';
import PropTypes from 'prop-types';
import axios from 'axios';
import './share-my-story.scss';
import FetchApiData from './fetch-api-data';

class ShareMyStory extends React.Component {

constructor(props) {
super(props);
this.state = {
smsData: ''
}
}

componentDidMount() {
const URL = '/js/feed/sms.json';
FetchApiData
.shareMyStoryData(URL)
.then((response) => {
this.setState({smsData: response });
})
.catch((error) => {
console.log(error);
});
}

render() {
console.log(this.state.smsData);
return (
<div>
<h1>{this.state.smsData.name}<h1>
<h2>{this.state.smsData.headline}</h2>
<h3><a href={this.state.smsData.link}>{this.state.smsData.link}</a></h3>
</div>
);
}
}

ShareMyStory.propTypes = {
name: PropTypes.string,
headline: PropTypes.string,
link: PropTypes.string,
smsData: PropTypes.array
}

DOM.render(
<ShareMyStory/>, document.getElementById('share-my-story'));

我有两个问题:

首先,我在 this.state.smsData 的 console.log 中未定义。

其次,我需要循环该对象并输出返回中的项目。我来自 Angular,所以我熟悉他们的迭代 ng-repeat,但我在 React 中没有看到类似的工具。有更好的方法来做到这一点吗?

最佳答案

1) 检查哪个先记录,也许当您触发 render() 时您的 fetchData 尚未完成。这就是您获得默认短信数据的原因。

2)为了循环数据,假设 dataArray 是您需要循环的数组

FetchApiData
.shareMyStoryData(URL)
.then((response) => {
// See if this is logging after Render is logged in
console.log('In FetchApiData: ', this.state.smsData);
this.setState({smsData: response });
})

render() {
console.log('In Render: ', this.state.smsData);

const listItems = this.state.dataArray.map(function(item) {
return (
<li key="{item.name}">
<a href="{item.link}">{item.name}</a>
</li>
);
});
return (<ul>{listItems}</ul>);
}

关于javascript - 从API访问数据并在react中输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940032/

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