我使用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传递给一个组件或由一个内部维护状态.在您的示例中,在不了解更多细节的情况下,似乎您唯一的选择是利用component state.这意味着您不能使用无状态组件,至少您要查看PureComponent或Component,即
原文链接:https://www.f2er.com/js/531267.htmlimport 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>
)
}