Javascript 从fetch()返回html并显示给用户
我使用fetch()进行API调用。然后() 使用application/json获取响应,我想将响应中的数据保存在html标记中,返回并显示给用户 从API中我得到25个结果,但我只想要前6个(通过使用for循环实现) 我想在代码中显示的console.log()中的内容是注释“Result should here” 我能和如何做到这一点 代码如下 我想在无状态/功能组件中使用它,因此不需要处理状态 顺便说一句,我对这一切都是新手,所以请温柔一点。谢谢Javascript 从fetch()返回html并显示给用户,javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,我使用fetch()进行API调用。然后() 使用application/json获取响应,我想将响应中的数据保存在html标记中,返回并显示给用户 从API中我得到25个结果,但我只想要前6个(通过使用for循环实现) 我想在代码中显示的console.log()中的内容是注释“Result should here” 我能和如何做到这一点 代码如下 我想在无状态/功能组件中使用它,因此不需要处理状态 顺便说一句,我对这一切都是新手,所以请温柔一点。谢谢 const Related = prop
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>
);
};
const-Related=props=>{
constURL=`/artist/${props.artistId}/related`;
常量getRelatedArtists=()=>{
获取(url)
.then(res=>res.json())
。然后(res=>{
var艺术家,姓名,numFans,img;
for(设i=0;i<6;i++){
艺术家=资源数据[i];
name=artist.name;
numFans=艺术家.nb_fan;
img=艺术家图片;
console.log(`
名称:${Name}
风扇:${numFans}
`);
}
})
.catch(err=>console.log(err));
};
返回(
相关艺术家
得到
{/*结果应该在这里*/}
);
};
我想要的结果是这样的:React是非常状态的,并且由props驱动——要么将props传递给组件,要么由一个组件在内部维护状态。在您的示例中,在不了解更多细节的情况下,您的唯一选择似乎是利用。这意味着您不能使用无状态组件,至少您会看到PureComponent
或组件
,即
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>
);
}
}
import React,{PureComponent}来自'React';
类相关组件{
状态={
艺术家:空,
错误:null
}
建造师(道具){
这个。超级();
this.url=`/artist/${props.artistId}/related`;
}
getRelatedArtists=async()=>{
试一试{
const res=wait fetch(this.url);
const json=await res.json();
this.setState({artists:json.data,error:null});
}捕获(e){
控制台错误(e);
this.setState({错误:'无法获取艺术家'});
}
}
渲染器(){
如果(!this.state.error)返回null;
返回(
{this.state.error}
)
}
渲染器列表(){
如果(!this.state.artists)返回null;
返回此.state.artists.map((x,i)=>(
名称:${x.Name}
粉丝:${x.nb_粉丝}
));
}
render(){
返回(
相关艺术家
获取{this.renderError()}
{this.renderatistList()}
);
}
}
如果你使用的是16。x,那么你应该考虑一下使用。下面是它作为功能组件的外观
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>
)
}
import React,{useState,useCallback}来自“React”;
功能相关(道具){
//设置状态
const[artists,setArtists]=useState(null);
const[error,setError]=useState(null);
//设置单击处理程序
const getRelatedArtists=useCallback(异步()=>{
试一试{
//从API获取数据
const res=wait fetch(`/artist/${props.artistId}/related`);
const json=await res.json();
//设定状态
setArtists(json.data);
设置错误(空);
}捕获(e){
控制台错误(e);
setError('无法获取艺术家');
}
},[props.artistId]);
//设置渲染辅助程序
功能渲染师(艺术家,关键点){
返回(
名称:${artist.Name}
粉丝:${artist.nb_Fans}
);
}
//渲染组件
返回(
相关艺术家
获取{error}
{artists&&artists.map(渲染师)}
)
}
使用react时,您需要利用react提供给您的优势,您应该拆分代码并使其可重用
第二:为了从一个大数组中的相关帖子中获取一些数字,您不需要进行循环,只需声明一个变量并将需要存储的帖子数量存储在其中即可
import React,{Component}来自'React';
从“./Post/Post”导入Post
类RelatedPosts扩展组件{
状态={
不动产:[],
}
componentDidMount(){
constURL=`/artist/${props.artistId}/related`;
获取(url)
。然后(响应=>{
const relatedPosts=response.data.slice(0,4),
latestRelatedPosts=relatedPosts.map(post=>{
返回{
邮递
}
})
;
这是我的国家({
不动产:最新的
});
}).catch(错误=>{
console.log(错误)
})
}
render(){
让relatedPosts=this.state.realted.map(realtedPost=>{
返回(
);
});
返回(
相关艺术家
{relatedPosts}
);
}
}
导出默认的相关帖子代码>可能重复@Sunil谢谢,但我想使用它而不带状态。如果可能(?)您必须使用状态或存储。若您使用的是功能组件,那个么您可以发送一个操作来更新您的存储(当您的API调用完成时)。存储更新将使用新数据重新呈现UI。在较新版本的react中,您可以通过react在无状态组件内部实现相同的功能。@Sunil是的,我将尝试hooksHey@James,谢谢您的帮助。我用React钩子包含了这段代码,并得到了错误:uncaughttypeerror:artists.map不是一个函数。现在怎么办?你能给我解释一下吗?@Zrna服务器的响应是什么样子的?我假设您正在接收一个JSON列表,但看起来不像