javascript - 从 fetch() 返回 html 并显示给用户
问题描述
我使用 fetch().then() 进行 API 调用 ...
使用 application/json 获取响应,我想将响应中的数据保存在 html 标记中,将其返回并显示给用户。
从 API 我得到 25 个结果,但我只想要前 6 个(通过使用 for 循环实现)。
console.log() 里面有什么我想在代码中显示注释“结果应该在这里”。
我可以以及如何实现它吗?
代码如下。
我想在无状态/功能组件中使用它,所以不处理状态。
顺便提一句。我是所有这一切的新手,所以请温柔。谢谢!
const Related = props => {
const url = `/artist/${props.artistId}/related`;
const getRelatedArtists = () => {
fetch(url)
.then(res => res.json())
.then(res => {
var artist, name, numFans, img;
for (let i = 0; i < 6; i++) {
artist = res.data[i];
name = artist.name;
numFans = artist.nb_fan;
img = artist.picture;
console.log(`
<div>
<p>Name: ${name}</p>
<p>Fans: ${numFans}</p>
<img src=${img} alt=${name} />
</div>
`);
}
})
.catch(err => console.log(err));
};
return (
<div>
<p>Related artists</p>
<button onClick={getRelatedArtists}>get</button>
{/* Result should be here */}
</div>
);
};
我想要的结果是这样的:https ://imgur.com/40dUyiw
解决方案
React 是非常状态和props驱动的 - 要么 props 被传递给组件,要么状态由内部维护。在您的示例中,在不了解更多细节的情况下,您唯一的选择似乎是利用组件状态。这意味着您不能使用无状态组件,至少您会查看 a PureComponent
or Component
ie
import React, { PureComponent } from 'react';
class Related extends PureComponent {
state = {
artists: null,
error: null
}
constructor(props) {
this.super();
this.url = `/artist/${props.artistId}/related`;
}
getRelatedArtists = async () => {
try {
const res = await fetch(this.url);
const json = await res.json();
this.setState({ artists: json.data, error: null });
} catch(e) {
console.error(e);
this.setState({ error: 'Unable to fetch artists' });
}
}
renderError() {
if (!this.state.error) return null;
return (
<span className="error">{this.state.error}</span>
)
}
renderArtistList() {
if (!this.state.artists) return null;
return this.state.artists.map((x,i) => (
<div key={i}>
<p>Name: ${x.name}</p>
<p>Fans: ${x.nb_fans}</p>
<img src=${x.picture} alt=${name} />
</div>
));
}
render() {
return (
<div>
<p>Related artists</p>
<button onClick={this.getRelatedArtists}>get</button> {this.renderError()}
{this.renderArtistList()}
</div>
);
}
}
如果您使用的是 React 16.x,那么您或许应该考虑使用Hooks。这是一个函数组件的外观
import React, { useState, useCallback } from 'react';
function Related(props) {
// setup state
const [artists, setArtists] = useState(null);
const [error, setError] = useState(null);
// setup click handler
const getRelatedArtists = useCallback(async () => {
try {
// fetch data from API
const res = await fetch(`/artist/${props.artistId}/related`);
const json = await res.json();
// set state
setArtists(json.data);
setError(null);
} catch(e) {
console.error(e);
setError('Unable to fetch artists');
}
}, [props.artistId]);
// setup render helper
function renderArtist(artist, key) {
return (
<div key={key}>
<p>Name: ${artist.name}</p>
<p>Fans: ${artist.nb_fans}</p>
<img src=${artist.picture} alt=${artist.name} />
</div>
);
}
// render component
return (
<div>
<p>Related artists</p>
<button onClick={getRelatedArtists}>get</button> {error}
{artists && artists.map(renderArtist)}
</div>
)
}
推荐阅读
- javascript - 如何使用 componentDidMount() 发出多个 axios.get() 请求并将第一个响应值分配给第二个?
- reactjs - 如何重用组件并使其在反应中通用?
- postgresql - 无法将数据输入到具有相互关联的外键的表中
- maven - Maven 安装在战争文件的最终名称中添加版本 ID
- android - 为什么零食的文字只显示一次?
- java - 高山 x86 上的 JDK 11
- android - Android 版本从 APK 迁移到 App Bundle
- sql - 如何使用过去两周的大查询获取 firebase 控制台事件详细信息,例如 first_open、app_remove 和 Registration_Success?
- spring - 如何从 JDBC 查询中获取值的类型?
- c++ - 为什么我的正则表达式在 JavaScript 中有效,但在 C++ 中无效?