从fetch()返回html并显示给用户

时间:2019-04-07 09:43:40

标签: javascript reactjs api fetch

我使用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

2 个答案:

答案 0 :(得分:2)

反应是非常状态 props 驱动的-要么将props 传递到组件,要么状态被保持由一个内部。在您的示例中,您可能不知道更多细节,但似乎唯一的选择是利用component state。这意味着您不能使用无状态组件,至少您要查看PureComponentComponent,即

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

答案 1 :(得分:0)

在使用react时,您需要利用react提供给您的优势,您应该拆分代码并使其可重用。

第二:为了从大型数组中获取相关帖子中的一些数字,您无需进行循环,您只需声明一个变量并将其存储在其中的帖子数即可

import React, {Component} from 'react';
import Post from './post/post'

class RelatedPosts extends Component{
    state = {
        realted: [],
    }
    componentDidMount(){
        const url = `/artist/${props.artistId}/related`;
        fetch(url)
            .then(response=>{
                const relatedPosts = response.data.slice(0 ,4),
                    latestRelatedPosts = relatedPosts.map(post=>{
                        return {
                            post
                        }
                    })
                ;
                this.setState({
                    realted: latestRelatedPosts
                });
            }).catch(error=>{
                console.log(error)
            })
    }
    render() {
        let relatedPosts = this.state.realted.map(realtedPost=>{
            return (
                <Post post={realtedPost}/>
            );
        });
        return (
            <section className="Posts">
                <p>Related artists</p>
                {relatedPosts}
            </section>
        );
    }
}
export default RelatedPosts;

在这里,我在componentDidMount生命周期中创建了请求,因为在将组件插入树中后会立即调用该请求,您可以找到更多信息here

在这里,我将创建一个新组件,以简化代码,以便以后维护,如果您以后想要更改任何内容,我会将来自我请求响应的数据传递给它

import React from 'react';
const post = (props) => (
    <article className="relatedPost">
        <h1>Name: {props.post.Name}</h1>
        <h1>Fans: {props.post.numFans}</h1>
        <img src={img} alt={name} />
    </article>
);
export default post