首页 > 解决方案 > 从 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

标签: javascriptreactjsapifetch

解决方案


React 是非常状态props驱动的 - 要么 props 被传递给组件,要么状态由内部维护。在您的示例中,在不了解更多细节的情况下,您唯一的选择似乎是利用组件状态。这意味着您不能使用无状态组件,至少您会查看 a PureComponentor Componentie

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

推荐阅读